TypeScript Arrays
An array in TypeScript has a single element type: every item must match it. The compiler then knows what you get back when you read an element, loop over the array or call methods like map and filter.
Declaring array types
There are two equivalent ways to write an array type:
| Syntax | Example |
|---|---|
Type[] (most common) |
string[], number[] |
Array<Type> (generic form) |
Array<string>, Array<number> |
const fruits: string[] = ["mango", "lychee", "durian"];
const primes: Array<number> = [2, 3, 5, 7];
fruits.push("rambutan");
console.log(fruits);
console.log(primes.length, primes[2]);[ 'mango', 'lychee', 'durian', 'rambutan' ]
4 5
The element type is enforced on every operation that adds data:
const primes: number[] = [2, 3, 5];
primes.push("seven");
primes[3] = true;main.ts(2,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
main.ts(3,1): error TS2322: Type 'boolean' is not assignable to type 'number'.
Inference for arrays
When you initialise an array with values, TypeScript infers the element type. Mixed values produce a union element type:
const scores = [90, 72, 85]; // number[]
const mixed = [1, "two", 3]; // (string | number)[]
const best = Math.max(...scores);
console.log(best);
for (const item of mixed) {
if (typeof item === "string") {
console.log("text:", item.toUpperCase());
} else {
console.log("number:", item * 10);
}
}90
number: 10
text: TWO
number: 30
Note: An empty array literal gives TypeScript nothing to infer from, so annotate it:
const ids: number[] = [];.
Array methods are typed too
Because the element type is known, callbacks get typed parameters automatically, and results have the right type:
interface Product {
title: string;
price: number;
}
const cart: Product[] = [
{ title: "Keyboard", price: 45 },
{ title: "Mouse", price: 20 },
{ title: "Monitor", price: 180 },
];
const titles = cart.map((p) => p.title); // string[]
const cheap = cart.filter((p) => p.price < 50); // Product[]
const total = cart.reduce((sum, p) => sum + p.price, 0); // number
const monitor = cart.find((p) => p.title === "Monitor"); // Product | undefined
console.log(titles);
console.log(cheap.length, total);
console.log(monitor?.price);[ 'Keyboard', 'Mouse', 'Monitor' ]
2 245
180
Notice that find returns Product | undefined: the item might not exist, and TypeScript makes you deal with that (here with ?.).
Readonly arrays
Add the readonly modifier (or use ReadonlyArray<T>) to forbid any change to the array. Methods such as push, pop and sort disappear from the type, and index assignment is rejected:
const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
weekdays.push("Sat");
weekdays[0] = "Monday";main.ts(3,10): error TS2339: Property 'push' does not exist on type 'readonly string[]'.
main.ts(4,1): error TS2542: Index signature in type 'readonly string[]' only permits reading.
Non-mutating methods like map, slice and toSorted still work, because they return a new array:
const weekdays: readonly string[] = ["Wed", "Mon", "Fri"];
const sorted = weekdays.toSorted();
console.log(sorted, weekdays);[ 'Fri', 'Mon', 'Wed' ] [ 'Wed', 'Mon', 'Fri' ]
Tip: Use
readonly T[]for function parameters you only read. It documents your intent and lets callers pass readonly arrays too.
Indexing can return undefined
By default, TypeScript assumes arr[i] always returns an element, even if the index is out of range:
const letters: string[] = ["a", "b"];
const third = letters[5]; // type string, but the value is undefined!The compiler option noUncheckedIndexedAccess makes the type string | undefined instead, forcing a check. It's not part of strict, but many teams enable it.
Multi-dimensional arrays
Arrays of arrays are written number[][]:
const grid: number[][] = [
[1, 0, 1],
[0, 1, 0],
];Test yourself
Which two annotations are equivalent?
string[]andArray<string>string[]and[string]Array<string>andstringstring[]andreadonly string[]
What is the inferred type of [1, "a", 2]?
- any[]
- number[]
- (string | number)[]
- [number, string, number]
Which call is NOT allowed on a readonly number[]?
- map
- slice
- push
- includes