...

/

Mutable and Immutable Arrays

Mutable and Immutable Arrays

In this lesson, you will learn about two different syntaxes to define an array.

Mutable arrays

Arrays in TypeScript are exactly like the ones in JavaScript in terms of features. The difference is that TypeScript assigns a type to the list.

The syntax, as shown below, utilizes square brackets [] with the actual type before the brackets and after the colon : like so:

Press + to interact
let a: number[];

It is also possible to initialize values during the declaration. In the following example, the two arrays are typed. TypeScript infers that the first one is a number and the second is a string. You can move your cursor over the two variables to see the types.

Press + to interact
let arrayOfNumber = [1, 2, 3];
let arrayOfString = ["string", "array", "only"];

Using multiple types will require you to evaluate what the type of each value is before using an individual item of the array. This is because the variable’s operations are type-dependent. There is an equivalent syntax that uses the ...