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:

typescriptinterface 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:

typescriptlet arr: User[] = [];

Let's fill our array with data of the specified type:

typescriptarr.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:

typescriptlet arr: Date[] = [];

Let's fill this array with dates:

typescriptarr.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:

typescriptlet arr: HTMLElement[] = [];

Let's fill our array with data:

typescriptlet lst: NodeList = document.querySelectorAll('div');
let arr: HTMLElement[] = Array.from(lst);

Practical tasks

Задание 1

Make an array whose elements will be regular expressions.

Задание 2

Make an array whose elements will be promises.

Задание 3

Make an interface that describes a worker. Make an array of objects with these workers.