TypeScript Arrays
TypeScript arrays let you describe collections of values with a single, consistent element type, catching mismatched items before your code runs.
Declaring typed arrays
An array type in TypeScript is written as the element type followed by square brackets, such as number[] or string[]. Equivalently, you can use the generic form Array<number>. Both mean exactly the same thing; the square-bracket form is more common in everyday code.
Example
let temperatures: number[] = [72, 68, 75, 80];
let labels: Array<string> = ["Mon", "Tue", "Wed"];
temperatures.push(90); // allowed - 90 is a number
// temperatures.push("hot"); // Error: Argument of type 'string' is
// not assignable to parameter of type 'number'.Arrays of union types and objects
Array elements are not limited to primitives. You can describe arrays whose items can be one of several types using a union, or arrays of a specific object shape. Wrapping a union in parentheses before adding [] is important - (string | number)[] differs from string | number[].
Example
// Array where each item is either a string or a number
let mixed: (string | number)[] = ["id-1", 2, "id-3", 4];
// Array of objects with a defined shape
let users: { name: string; age: number }[] = [
{ name: "Sam", age: 24 },
{ name: "Lee", age: 31 }
];
users.forEach(u => console.log(`${u.name} is ${u.age}`));Multidimensional arrays and readonly arrays
Arrays can be nested to represent grids or matrices by adding another pair of square brackets. When you want to guarantee that an array is never mutated after creation, mark it readonly - the compiler will then block push, pop, sort, splice, and index assignment on that array.
- number[][] - an array of arrays of numbers, e.g. a 2D grid.
- readonly string[] or ReadonlyArray<string> - an array that cannot be modified after creation.
- Type inference works for array literals too - let nums = [1, 2, 3] is inferred as number[].
- Empty array literals (let arr = []) are inferred as any[] unless annotated explicitly.
Example
let grid: number[][] = [
[1, 2, 3],
[4, 5, 6]
];
const frozenColors: readonly string[] = ["red", "green", "blue"];
// frozenColors.push("yellow"); // Error: Property 'push' does not
// exist on type 'readonly string[]'.
console.log(grid[1][2]); // 6Exercise: TypeScript Arrays
Which syntax declares an array of numbers in TypeScript?