How to declare an empty array in TypeScript

In TypeScript, declaring an empty array is a common task when developing applications. Having specific types ensures that your arrays maintain consistent data and reduces runtime errors. This guide will walk you through different ways to declare an empty array in TypeScript.

Declaring a basic empty array

The simplest way to declare an empty array in TypeScript is:

let myArray = [];

This approach declares an array named myArray that can hold any type of value.

Strongly typed arrays

To ensure type safety, you can declare an array with a specific type. Here's how you can declare an empty array of numbers:

let numbers: number[] = [];

Similarly, for strings:

let names: string[] = [];

Using the Array generic type

Another method to declare an empty array with type safety is by using the Array generic type:

let numbers: Array<number> = [];

And for strings:

let names: Array<string> = [];

Declaring arrays of custom types

If you have custom types, like interfaces or classes, you can also declare an empty array for them. Given an interface Person:

interface Person { name: string; age: number; }

You can declare an empty array of Person like this:

let people: Person[] = [];

Or using the Array generic type:

let people: Array<Person> = [];

Using tuple types

Tuple types allow you to declare an array where the type of a fixed number of elements is known but does not have to be the same. If you need an array that will always have a string and then a number, you can declare it like this:

let tupleArray: [string, number] = ['', 0];

Keep in mind that while this initializes the tuple with values, they are essentially placeholders, and you can later overwrite them.

Conclusion

Declaring empty arrays in TypeScript is straightforward once you know the type you want to work with. Using strongly typed arrays ensures that your code remains type-safe, preventing unexpected runtime errors. Remember to choose the method that best fits your needs and the readability of your code.

Invite only

We're building the next generation of data visualization.