TypeScript Data Types: The Ultimate Beginner-Friendly Guide
Learn TypeScript data types with simple explanations, interactive examples, visual learning, and interview questions.
If you have already learned TypeScript variables, you are ready for the next important step: TypeScript data types.
Don’t let the words “data type” scare you.
A data type is simply a way of telling TypeScript what kind of thing a value is.
Think about a child’s toy room.
You may have a box for cars, a box for dolls, a box for balls, a box for books, and a box for crayons.
You don’t randomly throw everything into every box. You know that a car is a car, a book is a book, and a ball is a ball.
TypeScript works in a similar way.
It helps us describe what kind of information a variable contains.
let name: string = "Rahul";
let age: number = 10;
let isStudent: boolean = true;
Here:
- name → text
- age → number
- isStudent → true/false
Simple definition: A data type tells TypeScript what kind of value something is.
What You Will Learn
By the end of this tutorial, you will understand:
- What a data type is
- Why TypeScript needs data types
stringnumberboolean- Arrays
- Tuples
- Objects
anyunknownnullundefined- Union types
- Literal types
voidnever- Type inference
- Type narrowing
- Real-world examples
- Playwright examples
- Interview questions
- Practice challenges
Meet the TypeScript Type Detective
Before learning individual types, imagine that TypeScript is a little detective.
It looks at a value and asks:
If it sees:
10
it understands that the value is a number.
If it sees:
"Hello"
it understands that the value is a string.
If it sees:
true
it understands that the value is a boolean.
Why Do We Need Data Types?
Imagine you have a box.
You put a number inside it:
let age: number = 25;
This tells TypeScript:
If you later write:
age = "twenty five";
TypeScript can tell you that something is wrong.
Think of TypeScript as a safety guard. It doesn’t stop you from building your application. It simply helps catch many mistakes before they become runtime problems.
TypeScript Data Types at a Glance
| Type | What It Stores | Example |
|---|---|---|
string | Text | "Hello" |
number | Numbers | 100 |
boolean | True/false | true |
| Array | List of values | [1,2,3] |
| Tuple | Fixed structure | ["Rahul",10] |
| Object | Related properties | {name:"Rahul"} |
any | Almost anything | any |
unknown | Unknown value | unknown |
null | Intentional absence | null |
undefined | Missing/unassigned | undefined |
| Union | One of multiple types | string | number |
void | No useful return | void |
never | Never normally completes | never |
1. String: The Type for Text
A string represents text.
let name: string = "Rahul";
Other examples:
let firstName: string = "Deepesh";
let city: string = "Indore";
let message: string = "Welcome to TypeScript";
Interactive Example: String
let name: string = "Rahul";
console.log(name);
"Rahul" with your own name and predict the output.
2. Number: The Type for Numbers
The number type represents numeric values.
let age: number = 10;
let price: number = 999;
let marks: number = 95;
let temperature: number = 32.5;
number for both integer-like and decimal numeric values.
Interactive Number Challenge
let price: number = 100;
let quantity: number = 3;
let total = price * quantity;
console.log(total);
Answer: 300
3. Boolean: The Yes-or-No Type
A boolean has only two values:
let isLoggedIn: boolean = true;
let testPassed: boolean = false;
Think about a light switch:
OFF → false
Interactive Boolean Challenge
const age = 20;
const isAdult = age >= 18;
console.log(isAdult);
true
4. Arrays: One Box With Many Values
An array stores multiple values.
Imagine five toy cars. Instead of using five separate boxes, you can put them into one larger box.
const numbers: number[] = [10, 20, 30, 40];
You can also write:
const numbers: Array<number> = [10, 20, 30, 40];
Array Indexes
const fruits: string[] = [
"Apple",
"Banana",
"Mango"
];
console.log(fruits[1]);
Banana
5. Tuple: A Special Kind of Array
A tuple looks like an array, but each position can have a specific type.
let student: [string, number] = ["Rahul", 10];
That means:
- Position 0 →
string - Position 1 →
number
Array = many similar things.
Tuple = fixed seats with specific jobs.
6. Object: A Box With Named Compartments
An object groups related information.
const student = {
name: "Rahul",
age: 10,
grade: 5
};
You can access the information using:
console.log(student.name);
console.log(student.age);
7. any: The “Anything Goes” Type
Think of any as a box with no label.
let data: any = "Hello";
data = 100;
data = true;
data = {
name: "Rahul"
};
any removes much of TypeScript’s type-safety benefit. Use it only when there is a good reason.
8. unknown: The Mystery Box
Imagine receiving a box but not knowing what’s inside.
You shouldn’t immediately pretend it contains a toy car. First, you check.
let data: unknown = "Hello";
if (typeof data === "string") {
console.log(data.toUpperCase());
}
unknown means “I don’t know yet. Check me first.”
any vs unknown
| Feature | any |
unknown |
|---|---|---|
| Can hold any value? | Yes | Yes |
| Type checking | Mostly disabled | Preserved |
| Requires narrowing? | No | Yes |
| Safer choice? | Usually no | Usually yes |
any → “Do whatever you want.”unknown → “Check me before you use me.”
9. null: Intentionally Empty
null represents an intentional absence of a value.
let selectedUser = null;
A common real-world example is:
let selectedUser: User | null = null;
This means the variable can contain a User, or intentionally contain no user.
10. undefined: Nothing Has Been Provided
undefined commonly means that a value hasn’t been assigned or isn’t currently available.
let nickname: string | undefined;
null → “I intentionally have no value.”undefined → “A value hasn’t been provided.”
11. Union Types: This OR That
A union type allows a variable to contain one of several known types.
let userId: string | number;
Both are valid:
userId = 101;
userId = "USER101";
But this is not:
userId = true;
| symbol means OR.
Interactive Union Challenge
Which assignments are valid?
let id: string | number;
id = 100;id = "ABC100";id = true;
boolean isn’t part of the union.
12. Literal Types: Only These Exact Values
A literal type allows only specific values.
let browser: "Chrome" | "Firefox" | "Safari";
These are valid:
browser = "Chrome";
browser = "Firefox";
But:
browser = "Edge";
would not match the declared type.
13. void: A Function That Returns Nothing Useful
You’ll usually see void as a function return type.
function sayHello(): void {
console.log("Hello");
}
The function performs an action but doesn’t return a useful value.
14. never: A Function That Never Normally Finishes
never is more advanced.
For example, a function that always throws an error never successfully returns:
function throwError(message: string): never {
throw new Error(message);
}
never means normal completion never happens.
Type Inference: TypeScript Is a Detective
You don’t always have to explicitly specify a type.
const name = "Rahul";
const age = 10;
const passed = true;
TypeScript can infer:
- name →
string - age →
number - passed →
boolean
This is called type inference.
Type Narrowing: Let TypeScript Find the Right Type
Sometimes a value can have multiple types.
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
if (typeof value === "number") {
console.log(value.toFixed(2));
}
}
At first TypeScript thinks:
After the typeof check, TypeScript can narrow the value to the appropriate type.
TypeScript Data Types in Playwright
If you are learning TypeScript for Playwright automation, these concepts become very practical.
const baseUrl: string = "https://example.com";
const timeout: number = 30000;
const headless: boolean = true;
const browsers: string[] = [
"chromium",
"firefox",
"webkit"
];
Now your framework clearly communicates what each value represents.
Test Data Example
const username: string = "testuser";
const password: string = "Password123";
const rememberMe: boolean = true;
const retryCount: number = 3;
These values can then be used by your Playwright tests.
Real-World API Example
Imagine an API returns a user ID as either a number or a string.
let userId: string | number;
This is better than using any because you’ve clearly documented the two allowed possibilities.
Common Beginner Mistakes
Mistake 1: Using any Everywhere
Using any simply because TypeScript reports an error defeats much of the purpose of TypeScript.
Mistake 2: Confusing Arrays and Tuples
string[]
means an array of strings.
[string, number]
means a tuple with a string followed by a number.
Mistake 3: Using String Instead of string
Prefer the lowercase primitive type:
let name: string;
rather than using the boxed-object form:
let name: String;
Must-Know TypeScript Data Type Interview Questions
Interview Tip: Don’t just memorize the answer. Understand the simple idea behind it. Interviewers often ask follow-up questions.
1. What are data types in TypeScript?
string, number, boolean, arrays, tuples, objects, unions, and other TypeScript types.
2. What are the common primitive types?
string, number, boolean, bigint, symbol, null, and undefined.
3. What is the difference between any and unknown?
any largely disables type checking for the value. unknown can hold any value, but TypeScript requires you to narrow or check the value before performing type-specific operations.
4. What is a union type?
let id: string | number;
5. What is the difference between an array and a tuple?
6. What is type inference?
const age = 25;
TypeScript infers age as a number.
7. What is never?
never represents a value that never occurs. It is commonly used for functions that never successfully complete, such as functions that always throw an error.
8. What is void?
void is commonly used for functions that do not return a useful value.
9. What is the difference between null and undefined?
null usually represents an intentional absence of a value, while undefined commonly indicates that a value has not been assigned or provided.
10. Does TypeScript have separate integer and floating-point types?
number type.
Scenario-Based Interview Questions
Scenario 1: API Returns String or Number
An API sometimes returns:
101
and sometimes:
"101"
Answer:
let userId: string | number;
Scenario 2: Completely Unknown API Response
Would you use any or unknown?
unknown when the data is genuinely unknown and you can validate or narrow it before using it.
Scenario 3: Browser Configuration
Your automation framework supports only:
- chromium
- firefox
- webkit
A literal union is a good choice:
type BrowserName =
| "chromium"
| "firefox"
| "webkit";
This prevents accidental values outside the supported list.
Final Interactive Type Detective Challenge
Don’t look at the answer immediately. Try to identify the type of every variable.
const name = "Deepesh";
const age = 35;
const isTrainer = true;
const skills = [
"Python",
"Playwright",
"TypeScript"
];
const employee: [string, number] = [
"Deepesh",
35
];
const id: string | number = 101;
Answer
- name →
string - age →
number - isTrainer →
boolean - skills →
string[] - employee →
[string, number] - id →
string | number
Practice Programs
Don’t stop after reading. Try these exercises yourself.
Practice 1: Student Information
Create variables for:
- Name
- Age
- Grade
- Whether the student passed
Practice 2: Shopping Cart
Create variables for product name, price, quantity, and stock status. Calculate the total price.
Practice 3: Employee
Create an employee object containing ID, name, department, experience, and active status.
Practice 4: Browser Configuration
Create a literal union containing chromium, firefox, and webkit.
Practice 5: User ID
Create a variable that accepts a number or string but rejects a boolean.
TypeScript Data Types Cheat Sheet
| Type | Easy Meaning | Example |
|---|---|---|
string | Words/text | "Hello" |
number | Numbers | 100 |
boolean | Yes/no | true |
| Array | List | [1,2,3] |
| Tuple | Fixed positions | ["A",10] |
| Object | Related information | {name:"A"} |
any | Anything | any |
unknown | Mystery value | unknown |
null | Intentionally empty | null |
undefined | Not provided | undefined |
| Union | This OR that | string | number |
void | No useful return | void |
never | Never normally completes | never |
Final Takeaway
If you are a beginner, don’t try to memorize every TypeScript type today.
Instead, remember the idea behind each one.
String → text
Number → numbers
Boolean → yes or no
Array → collection
Tuple → fixed structure
Object → related information
any → “Don’t check me.”
unknown → “Check me first.”
Union → “This OR that.”
void → “I don’t return a useful value.”
never → “Normal completion never happens.”
Don’t just read TypeScript. Practice it.
Write code. Break it. Read the error. Fix it. Repeat.
Frequently Asked Questions
What are the most important TypeScript data types for beginners?
Start with string, number, boolean, array, and object. Then learn tuples, unions, any, unknown, null, and undefined. After that, move into literal types, void, never, generics, and utility types.
Is any bad in TypeScript?
any is not forbidden, but excessive use removes much of TypeScript’s type-safety benefit. When a value is genuinely unknown, unknown is often a safer choice.
What is the difference between an array and a tuple?
An array generally represents a collection of values, while a tuple represents a fixed structure where each position can have a specific type.
What is a union type?
A union type allows a value to be one of several possible types. For example, string | number means the value can be a string or a number.
Why is unknown safer than any?
With unknown, TypeScript requires you to check or narrow the value before performing operations that depend on a particular type. With any, those checks are largely bypassed.
Learning Tip: Save this article and revisit the cheat sheet whenever you forget a TypeScript data type. The fastest way to master these concepts is to write small programs and predict their output before running them.