In TypeScript, an array of objects can be created by using the Array<T>
type, where T
is the type of the objects that the array will contain.
Here is an example of how to create and use an array of objects in TypeScript:
interface Person {
name: string;
age: number;
}
const people: Array<Person> = [
{name: 'John', age: 30},
{name: 'Jane', age: 25},
{name: 'Bob', age: 35}
];
console.log(people); // [{name: 'John', age: 30}, {name: 'Jane', age: 25}, {name: 'Bob', age: 35}]
// Accessing properties of an object in the array
console.log(people[0].name); // John
In this example, we have defined an interface called Person
with the properties name
and age
. We then created an array of Person
objects called people
and added three objects to the array. We can access the properties of the objects in the array using dot notation, as shown in the last line of the example.