Declare an Empty Array for a typed Variable in TypeScript

avatar

Borislav Hadzhiev

Wed Feb 16 20222 min read

Declare an Empty Array for a typed Variable in TypeScript #

To declare an empty array for a type variable, set the array's type to Type[], e.g. const arr: Animal[] = []. Any elements you add to the array need to conform to the specific type, otherwise you would get an error.

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

We declared the arr variable, setting it to an empty array of type Animal[].

This means that any element we add to the array needs to be of type Animal, otherwise we would get an error.

index.ts
type Animal = { name: string; age: number; }; const arr: Animal[] = []; // ⛔️ Error: Argument of type {test: string} is not // assignable to parameter of type 'Animal' arr.push({ test: 'hello' });

The object we tried to push to the array does not satisfy the Animal type, so TypeScript errors out.

TypeScript would also warn you if you forget to add a property that is required on the specific type.

index.ts
type Animal = { name: string; age: number; }; const arr: Animal[] = []; // ⛔️ Error: Property of type 'age' is missing // but required in type Animal arr.push({ name: 'Alfred' });

Alternatively, you can use a type assertion to declare an empty array of a specific type.

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

When using type assertions, we are effectively telling TypeScript that we know better and the arr variable is definitely of type Animal[].

Type assertions are often used when fetching data from a remote source like a database because TypeScript likely doesn't know the type of the data you fetch with an API request.

When using type assertions, we would also get errors when we try to push a value to the array that doesn't conform to the specified type.

index.ts
type Animal = { name: string; age: number; }; const arr = [] as Animal[]; // ⛔️ Error: Property of type 'age' is missing // but required in type Animal arr.push({ name: 'Alfred' }); // ⛔️ Error: Argument of type {test: string} // is not assignable to parameter of type Animal arr.push({ test: 'hello' });

Which approach you pick is a matter of personal preference. In this situation I'd go with the first approach as there is no real need for a type assertion.

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