Push an object to an Array in TypeScript

avatar

Borislav Hadzhiev

Tue Feb 15 20222 min read

banner

Photo by Brooke Cagle

Push an object to an Array in TypeScript #

To push an object to an array:

  1. Set the type of the array to Type[].
  2. Set the type of the object to Type.
  3. Use the push() method to push the object to the array.
index.ts
interface Animal { name: string; age: number; } const arr: Animal[] = []; const a1: Animal = { name: 'Alfred', age: 3, }; arr.push(a1); // 👇️ [{name: 'Alfred', age: 3}] console.log(arr);

We set the type of the array to Animal[], so we are able to push objects of type Animal to it using the Array.push method.

If you are getting the object from a remote source, e.g. a database, you might have to assert its type.

index.ts
interface Animal { name: string; age: number; } const arr: Animal[] = []; const a1 = { name: 'Alfred', age: 3, } as unknown as Animal; // 👈️ type assertion arr.push(a1); // 👇️ [{name: 'Alfred', age: 3}] console.log(arr);
Sometimes we have information about the type of a value that TypeScript can't know about. This is often the case when fetching data from a remote API.

In this scenario, we can use a type assertion to set the object to a specific type, so we are able to push it to the array.

If you only have the values the object should contain, you must create the object before pushing it to the array.

index.ts
interface Animal { name: string; age: number; } const arr: Animal[] = []; const a1 = {} as Animal; a1.name = 'Alfred'; a1.age = 3; arr.push(a1); // 👇️ [{name: 'Alfred', age: 3}] console.log(arr);

On the other hand, if you have multiple objects, you can pass them as comma-separated values to the push() method and push them to the array in the same call to the method.

index.ts
interface Animal { name: string; age: number; } const arr: Animal[] = []; const a1: Animal = { name: 'Alfred', age: 3, }; const a2: Animal = { name: 'Fred', age: 2, }; arr.push(a1, a2); // 👇️ [{name: 'Alfred', age: 3}, {name: 'Fred', age: 2}] console.log(arr);

The push method takes one or more values and pushes them to the array, so we are able to pass it multiple, comma-separated objects as parameters.

Use the search field on my Home Page to filter through my more than 1,000 articles.