How To Declare An Empty Array In TypeScript?

Tim Mouskhelichvili
Tim Mouskhelichvili
2 minutes to read

When declaring an empty array in TypeScript, the compiler cannot infer its type by default. That's why you need to specify the array's type explicitly. Luckily, it is easy to do.

Here is one way to declare an empty array of objects in TypeScript:

typescriptinterface IPerson {
    name: string;
    age: number;
}

const persons: IPerson[] = [];

This article provides the complete solution to declare an empty typed array in TypeScript, with many code examples.

Let's get to it 😎.

In TypeScript, when you declare an empty array (without specifying its type), the array's type is always any[].

Here is an example:

typescriptconst arr = [];

arr.push('Tim');

arr.push(27);

An array of type any[] doesn't have any validation, so you can add any item type you want to it.

How to declare an empty typed array?

You have a few options to create an empty typed array in TypeScript.

1. Explicitly declare the type

If you want to limit the types an empty array can accept, you can declare it explicitly.

Here is an example:

typescript// This array only accepts strings.
const strArr: string[] = [];
strArr.push('Tim');

// This array only accepts numbers.
const numArr: number[] = [];
numArr.push(27);

As you can see, those arrays only accept one specific type of item.

2. Declare via type assertion

Another option to limit the type of items an array accepts is to cast the array via type assertion.

Here is an example:

typescript// This array only accepts strings.
const strArr = [] as string[];
strArr.push('Tim');

// This array only accepts numbers.
const numArr = [] as number[];
numArr.push(27);

3. Declare using the Array constructor

The final option to limit array types is to use the Array constructor.

Here is an example:

typescript// This array only accepts strings.
const strArr = new Array<string>();
strArr.push('Tim');

// This array only accepts numbers.
const numArr = new Array<number>();
numArr.push(27);

How to declare an empty array of objects?

To declare an empty array of objects, you must pass the object's type to the array.

Here is how to do it:

typescriptinterface IArticle {
    content: string;
    date: Date;
};

const articles: IArticle[] = [];

Read more: How do interfaces work in TypeScript?

That way, you will only be able to add objects of type IArticle to that array.

If you try to add an object of another type, TypeScript will output an error.

Final thoughts

As you can see, declaring an empty typed array is simple.

You have multiple ways of doing it: explicitly, via type assertion, or using the Array constructor.

Use the one that you prefer!

typescript empty array

Here are some other TypeScript tutorials for you to enjoy:

Comments (1)
Reply to:
Rahul July 24, 2023 04:33AM
Thank you for the information.
REPLY