Series: TypeScript from Basics to Advanced
Part: 4 — Arrays & Objects
Level: Beginner → Intermediate
Introduction
In the previous articles, we learned:
-
What TypeScript is
-
Basic TypeScript types
-
How to type functions
So far, most of our examples have worked with individual values:
const name: string = "Sundar";
const age: number = 25;
const isDeveloper: boolean = true;
But real applications rarely work with individual values.
Instead, we work with collections and structured data:
Users
Products
Orders
Questions
Tests
Posts
Comments
API responses
For example, a user might look like this:
const user = {
id: 1,
name: "Sundar",
email: "sundar@example.com"
};
And an application might have many users:
const users = [
{
id: 1,
name: "Sundar"
},
{
id: 2,
name: "Rahul"
}
];
TypeScript allows us to describe the structure of this data and catch mistakes before runtime.
In this article, we'll learn how to work with arrays and objects in TypeScript.
1. Typing Arrays
Let's start with a simple array.
const numbers: number[] = [10, 20, 30, 40];
The syntax is:
type[]
So:
number[]
means:
An array containing numbers.
Similarly:
const names: string[] = [
"Sundar",
"Rahul",
"John"
];
Here:
string[]
means an array of strings.
2. Other Array Types
We can create arrays for different primitive types.
const numbers: number[] = [1, 2, 3];
const names: string[] = ["A", "B", "C"];
const statuses: boolean[] = [true, false, true];
TypeScript prevents us from adding an incorrect type.
For example:
const numbers: number[] = [1, 2, 3];
numbers.push("4");
TypeScript reports an error because "4" is a string.
The array expects:
number
not:
string
3. Using Array<T>
There is another syntax for defining arrays:
const numbers: Array<number> = [1, 2, 3];
This is equivalent to:
const numbers: number[] = [1, 2, 3];
For strings:
const names: Array<string> = [
"Sundar",
"Rahul"
];
Both styles are valid.
Which one should you use?
You'll commonly see:
string[]
for simple arrays.
And:
Array<string>
when working with generics or more complex types.
For example:
Array<User>
is common in TypeScript applications.
4. Arrays of Objects
This is where TypeScript becomes much more useful.
Consider:
const users = [
{
id: 1,
name: "Sundar",
email: "sundar@example.com"
},
{
id: 2,
name: "Rahul",
email: "rahul@example.com"
}
];
TypeScript can infer the structure of the objects.
But in real applications, we often want to explicitly define the structure.
For example:
type User = {
id: number;
name: string;
email: string;
};
Then:
const users: User[] = [
{
id: 1,
name: "Sundar",
email: "sundar@example.com"
},
{
id: 2,
name: "Rahul",
email: "rahul@example.com"
}
];
Now TypeScript knows exactly what every user should look like.
5. Why Arrays of Objects Matter
Arrays of objects are everywhere in modern applications.
For example, an e-commerce application might have:
type Product = {
id: number;
name: string;
price: number;
};
const products: Product[] = [
{
id: 1,
name: "Laptop",
price: 50000
},
{
id: 2,
name: "Phone",
price: 30000
}
];
A React application might have:
const [users, setUsers] = useState<User[]>([]);
A Node.js API might return:
Promise<User[]>
Understanding arrays of objects is therefore essential for real-world TypeScript development.
6. Object Types
Now let's look at objects.
We can define an object type directly:
const user: {
id: number;
name: string;
email: string;
} = {
id: 1,
name: "Sundar",
email: "sundar@example.com"
};
This tells TypeScript that user must contain:
id → number
name → string
email → string
If we try:
const user: {
id: number;
name: string;
} = {
id: "1",
name: "Sundar"
};
TypeScript reports an error because id should be a number.
7. Object Type Inference
Just like with variables and functions, TypeScript can infer object types.
const user = {
id: 1,
name: "Sundar",
email: "sundar@example.com"
};
TypeScript understands:
user.id → number
user.name → string
user.email → string
So you don't necessarily need to explicitly annotate every object.
However, when an object represents an important domain model, using a reusable type or interface is usually better.
We'll cover type and interface in the next article.
8. Optional Object Properties
Not every property is always required.
For example, a user may or may not have a profile picture.
We can use ?:
type User = {
id: number;
name: string;
profileImage?: string;
};
Now both are valid:
const user1: User = {
id: 1,
name: "Sundar"
};
And:
const user2: User = {
id: 2,
name: "Rahul",
profileImage: "profile.jpg"
};
The ? means the property is optional.
9. Optional Properties Can Be undefined
Consider:
type User = {
name: string;
email?: string;
};
If we access:
user.email
the value may be:
string
or:
undefined
Therefore, we should handle the possibility that it doesn't exist.
For example:
if (user.email) {
console.log(user.email.toLowerCase());
}
This is another example of TypeScript's type narrowing.
We'll explore narrowing in more detail later.
10. Readonly Properties
Sometimes we don't want a property to be changed after an object is created.
We can use:
readonly
Example:
type User = {
readonly id: number;
name: string;
};
Now:
const user: User = {
id: 1,
name: "Sundar"
};
This is allowed:
user.name = "Rahul";
But this is not:
user.id = 2;
because id is readonly.
TypeScript will report an error.
Readonly is useful for values that should be treated as immutable.
11. Readonly Arrays
We can also make an entire array readonly.
const numbers: readonly number[] = [1, 2, 3];
Now:
numbers.push(4);
is not allowed.
Another syntax is:
const numbers: ReadonlyArray<number> = [1, 2, 3];
Both represent a readonly array.
12. Nested Objects
Real application data is often nested.
For example:
type Address = {
city: string;
state: string;
country: string;
};
type User = {
id: number;
name: string;
address: Address;
};
Now:
const user: User = {
id: 1,
name: "Sundar",
address: {
city: "Hyderabad",
state: "Telangana",
country: "India"
}
};
TypeScript understands the complete structure.
We can access:
user.name;
and:
user.address.city;
TypeScript knows that:
user.address → Address
user.address.city → string
13. Arrays Inside Objects
Objects can contain arrays as well.
For example:
type User = {
id: number;
name: string;
skills: string[];
};
Now:
const user: User = {
id: 1,
name: "Sundar",
skills: [
"JavaScript",
"TypeScript",
"React"
]
};
We can access:
user.skills[0];
TypeScript knows the result is a string.
14. Objects Inside Arrays Inside Objects
Real applications can get more complex.
Consider an online test application:
type Option = {
id: string;
text: string;
};
type Question = {
id: string;
question: string;
options: Option[];
};
type Test = {
id: string;
title: string;
questions: Question[];
};
Now we can create:
const test: Test = {
id: "TEST_001",
title: "JavaScript Test",
questions: [
{
id: "Q1",
question: "What is JavaScript?",
options: [
{
id: "OPT1",
text: "A programming language"
},
{
id: "OPT2",
text: "A database"
}
]
}
]
};
This is a realistic example of TypeScript modeling complex application data.
15. Multidimensional Arrays
You can also create arrays containing other arrays.
For example:
const matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Here:
number[][]
means:
An array containing arrays of numbers.
You can also use:
const data: string[][] = [
["A", "B"],
["C", "D"]
];
16. Tuples
A tuple is different from a normal array.
With an array:
const values: (string | number)[] = [
"Sundar",
25
];
The array can contain strings and numbers in any order.
A tuple defines the exact position and type:
const user: [string, number] = [
"Sundar",
25
];
This means:
index 0 → string
index 1 → number
This is valid:
const user: [string, number] = [
"Sundar",
25
];
But this isn't:
const user: [string, number] = [
25,
"Sundar"
];
Tuples are useful when the position of each value has a specific meaning.
17. Union Types in Arrays
Sometimes an array legitimately contains multiple types.
For example:
const values: (string | number)[] = [
"Sundar",
25,
"React",
5
];
The parentheses are important:
(string | number)[]
This means:
An array where each element can be either a string or a number.
This is different from:
string | number[]
which means:
Either one string OR an array of numbers.
The placement of parentheses matters.
18. Objects With Dynamic Keys
Sometimes we don't know the property names ahead of time.
For example:
const scores = {
Sundar: 90,
Rahul: 85,
John: 95
};
We can describe this using an index signature:
type Scores = {
[username: string]: number;
};
Now:
const scores: Scores = {
Sundar: 90,
Rahul: 85,
John: 95
};
This means:
Any string key is allowed, but its value must be a number.
19. Record for Dynamic Objects
TypeScript also provides a utility type called Record.
The previous example can be written as:
type Scores = Record<string, number>;
This means the same thing:
string key → number value
For example:
const scores: Record<string, number> = {
Sundar: 90,
Rahul: 85
};
We'll explore Record and other utility types later in this series.
20. Function Parameters With Arrays and Objects
Now let's combine what we learned in Part 3.
Suppose we have:
type User = {
id: number;
name: string;
};
We can create a function that accepts a User:
function printUser(user: User): void {
console.log(user.name);
}
Or multiple users:
function printUsers(users: User[]): void {
users.forEach((user) => {
console.log(user.name);
});
}
TypeScript now knows that every element in users is a User.
This gives us autocomplete and type checking inside the function.
21. Returning Arrays and Objects From Functions
Functions can also return structured data.
For example:
function getUsers(): User[] {
return [
{
id: 1,
name: "Sundar"
},
{
id: 2,
name: "Rahul"
}
];
}
Or:
function getUser(): User {
return {
id: 1,
name: "Sundar"
};
}
With asynchronous APIs:
async function getUsers(): Promise<User[]> {
// API request
return [];
}
This combination of objects + arrays + functions is something you'll use constantly in React and Node.js applications.
22. Real-World React Example
Suppose we're building a React application.
We have:
type User = {
id: number;
name: string;
email: string;
};
Our state can be:
const [users, setUsers] = useState<User[]>([]);
Now TypeScript knows that users is:
User[]
When we iterate:
users.map((user) => {
return <div>{user.name}</div>;
});
TypeScript knows that:
user → User
So your editor can provide autocomplete for:
user.id
user.name
user.email
This is one of the biggest practical benefits of TypeScript in React applications.
23. A Practical API Response
Consider a backend API returning:
{
"status": "success",
"message": "Users fetched successfully",
"data": [
{
"id": 1,
"name": "Sundar"
},
{
"id": 2,
"name": "Rahul"
}
]
}
We could model it as:
type User = {
id: number;
name: string;
};
type UserResponse = {
status: string;
message: string;
data: User[];
};
Now the entire response has a known structure.
Later, we'll improve this pattern using generics, which allows us to create reusable API response types.
24. Common Mistakes
Mistake 1: Using any[]
Avoid:
const users: any[] = [];
This removes much of the benefit of TypeScript.
Prefer:
const users: User[] = [];
Mistake 2: Using Object
You might see:
const user: Object = {};
This is generally not useful.
Object doesn't describe the properties your object contains.
Instead, describe the actual structure:
type User = {
id: number;
name: string;
};
const user: User = {
id: 1,
name: "Sundar"
};
Mistake 3: Using object When You Need a Specific Shape
This:
const user: object = {};
only tells TypeScript that the value is an object.
It doesn't tell TypeScript:
id exists
name exists
email exists
A specific type is much more useful.
Mistake 4: Forgetting Optional Properties
If a property might not exist:
type User = {
name: string;
email?: string;
};
Don't pretend it is always available.
Handle the possibility of undefined.
Arrays vs Tuples
It's important to understand the difference.
Array
const user: (string | number)[] = [
"Sundar",
25
];
The elements can be reordered:
const user: (string | number)[] = [
25,
"Sundar"
];
This is still valid.
Tuple
const user: [string, number] = [
"Sundar",
25
];
The order matters.
index 0 → string
index 1 → number
Arrays & Objects Cheat Sheet
RequirementTypeScriptArray of numbersnumber[]Array of stringsstring[]Generic arrayArray<T>Array of usersUser[]Nested arraynumber[][]String or number array(string | number)[]Object{ name: string }Optional propertyemail?: stringReadonly propertyreadonly id: numberReadonly arrayreadonly number[]Tuple[string, number]Dynamic objectRecord<string, number>Nested objectaddress: Address
Best Practices
1. Define reusable types for important data structures
type User = {
id: number;
name: string;
};
2. Use User[] instead of any[]
const users: User[] = [];
3. Use optional properties when values can be missing
type User = {
name: string;
email?: string;
};
4. Use readonly when a value should not be modified
type User = {
readonly id: number;
};
5. Don't use object when you know the structure
Prefer:
type Product = {
id: number;
name: string;
price: number;
};
over:
let product: object;
6. Let TypeScript infer obvious structures
You don't need to annotate every local variable:
const numbers = [1, 2, 3];
TypeScript already knows it is:
number[]
Final Takeaway
Arrays and objects are the foundation of data modeling in TypeScript.
You should be comfortable writing:
const numbers: number[] = [1, 2, 3];
type User = {
id: number;
name: string;
};
const users: User[] = [];
type User = {
id: number;
name: string;
skills: string[];
};
And more complex structures:
type Question = {
id: string;
question: string;
options: Option[];
};
The key idea is:
Types allow us to describe the shape of the data our application works with.
Once you can model arrays and objects properly, you're ready to move into one of the most important TypeScript topics: reusable types and interfaces.