Defining an array of objects in TypeScript is a common practice, especially when working with multiple data entities that share the same structure. Defining an array of objects in TypeScript typically involves two steps: first, define the object type (typically using an interface or type alias), and then define the array type.
Step 1: Define the Object Type
You can use interfaces (interface) or type aliases (type) to define the structure of an object. For example, suppose we need to define an object representing a user; you can do the following:
typescriptinterface IUser { id: number; name: string; age: number; } // Or using a type alias type User = { id: number; name: string; age: number; };
Step 2: Define the Object Array
Once you have defined the object type, you can define an array of objects by appending [] to the type. For example:
typescriptlet users: IUser[] = []; // Push data into the array users.push({ id: 1, name: "Alice", age: 30 }); users.push({ id: 2, name: "Bob", age: 24 }); // Or using a type alias let users2: User[] = [ { id: 3, name: "Charlie", age: 28 }, { id: 4, name: "David", age: 22 } ];
Example Application
Suppose we are developing a simple application that needs to display a user list. First, we define the user type, then create an array of users and populate it with data, and finally process this data using functions, such as filtering users who are older than 25 years:
typescriptinterface IUser { id: number; name: string; age: number; } let users: IUser[] = [ { id: 1, name: "Alice", age: 30 }, { id: 2, name: "Bob", age: 24 }, { id: 3, name: "Charlie", age: 28 } ]; function filterUsersByAge(users: IUser[], minAge: number): IUser[] { return users.filter(user => user.age >= minAge); } let usersOver25 = filterUsersByAge(users, 25); console.log(usersOver25); // Output: [{ id: 1, name: "Alice", age: 30 }, { id: 3, name: "Charlie", age: 28 }]
This example demonstrates how to define and use arrays of objects in TypeScript, as well as how to manipulate these arrays to meet specific business requirements.