Arrays of Objects in TypeScript
Arrays in TypeScript can contain not only primitives, but also objects of certain types. Let's look at examples of how to work with such arrays.
Array of users
Let's say we have an interface that defines a user:
interface User {
name: string,
age: number
}
Let's declare an array, specifying objects with users (i.e. objects implementing our interface) as the type of its content:
let arr: User[] = [];
Let's fill our array with data of the specified type:
arr.push({name: 'john', age: 30});
arr.push({name: 'eric', age: 40});
Array of dates
Let's declare an array that stores an array of dates:
let arr: Date[] = [];
Let's fill this array with dates:
arr.push(new Date(2030, 11, 31));
arr.push(new Date(2020, 11, 31));
Array of DOM elements
Let's declare an array containing house elements:
let arr: HTMLElement[] = [];
Let's fill our array with data:
let lst: NodeList = document.querySelectorAll('div');
let arr: HTMLElement[] = Array.from(lst);
Practical tasks
Make an array whose elements will be regular expressions.
Make an array whose elements will be promises.
Make an interface that describes a worker. Make an array of objects with these workers.