How to Initialize an Array in TypeScript?

As a TypeScript developer, you should know how to work with arrays. In this tutorial, I will explain how to initialize an array in TypeScript with detailed examples. I will explain array initialization in TypeScript here with practical examples and best practices.

Why Use TypeScript Arrays?

TypeScript is a superset of JavaScript that adds static typing to the language. Arrays are a fundamental part of TypeScript, allowing you to store multiple values in a single variable. Using arrays in TypeScript can help you write more predictable and maintainable code, especially in larger applications.

Basic Array Initialization in TypeScript

To initialize an array in TypeScript, you can use the Array constructor or the square bracket ([]) syntax. Here’s how you can do it:

Using Square Brackets

The most common and straightforward method to declare and initialize an array in TypeScript is by using square brackets.

let cities: string[] = ['New York', 'Los Angeles', 'Chicago'];

In this example, we declare an array cities that can only contain string elements. We then initialize it with three city names.

Using the Array Constructor

You can also use the Array constructor to initialize an array.

let states: Array<string> = new Array('California', 'Texas', 'Florida');

This syntax is less common but equally effective. It declares an array states that holds string elements and initializes it with three state names.

Check out Sort Arrays in TypeScript

Initialize TypeScript Arrays with Specific Types

TypeScript allows you to define the type of elements stored in an array. This ensures type safety and helps catch errors during development.

Number Arrays

let temperatures: number[] = [72, 85, 90, 68];

In this example, the temperatures array is specified to hold numbers only.

Boolean Arrays

let flags: boolean[] = [true, false, true];

The flags array is declared to store boolean values.

Arrays of Objects

You can also initialize arrays of objects, which is particularly useful for more complex data structures.

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

let people: Person[] = [
    { name: 'John Doe', age: 30, city: 'New York' },
    { name: 'Jane Smith', age: 25, city: 'Los Angeles' },
    { name: 'Mike Johnson', age: 35, city: 'Chicago' }
];

In this example, we define an interface Person and create an array people that holds objects of type Person.

Check out Filter Arrays in TypeScript

Multi-Dimensional Arrays Initialization

TypeScript also supports multi-dimensional arrays, which are arrays of arrays. Let me show you how to initialize multi-dimensional arrays in TypeScript.

Two-Dimensional Arrays

Here is how to initialize a two-dimensional array in TypeScript.

let matrix: number[][] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

Here, matrix is a two-dimensional array where each element is itself an array of numbers.

Three-Dimensional Arrays

Here is an example of initializing a three-dimensional array.

let cube: number[][][] = [
    [
        [1, 2, 3],
        [4, 5, 6]
    ],
    [
        [7, 8, 9],
        [10, 11, 12]
    ]
];

In this example, cube is a three-dimensional array.

Read Append Elements to an Array in TypeScript

Advanced Array Initialization Techniques in TypeScript

Now, let me show you some advanced array initialization techniques in TypeScript with examples.

Using the Spread Operator

The spread operator (...) allows you to create a new array by expanding the elements of an existing TypeScript array.

let originalArray: number[] = [1, 2, 3];
let newArray: number[] = [...originalArray, 4, 5, 6];
console.log(newArray); // Output: [1, 2, 3, 4, 5, 6]

Here is the exact output in the screenshot below:

Initialize an Array in TypeScript

Using Array.from

The Array.from method creates a new array from an array-like or iterable object.

let stringArray: string[] = Array.from('hello');
console.log(stringArray); // Output: ['h', 'e', 'l', 'l', 'o']

Using Array.of

The Array.of method creates a new array with a variable number of arguments, regardless of number or type of the arguments.

let mixedArray: any[] = Array.of(1, 'two', true, { name: 'Alice' });
console.log(mixedArray); // Output: [1, 'two', true, { name: 'Alice' }]

Read Check if a TypeScript Array Contains a Specific Value

Common Errors and How to Avoid Them

Now, let me show you some common errors and how to avoid them while initializing a TypeScript array.

Type Inference Issues

TypeScript can infer the type of an array if it is initialized with values. However, if the array is initially empty, the type must be explicitly declared.

let emptyArray: number[] = [];
emptyArray.push(10); // Correct

Ensuring Type Safety

Always specify the type of elements in an array to avoid runtime errors.

let mixedArray: any[] = [1, 'two', true];
mixedArray.push({ name: 'Alice' }); // Allowed, but not type-safe

Instead, define a union type if the array should hold multiple types.

let safeArray: (number | string | boolean)[] = [1, 'two', true];
safeArray.push('three'); // Correct

Conclusion

In this tutorial, I explained how to initialize an Array in TypeScript using various examples.

You may also like: