Skip to main content

Array Type

Declaring an array's element type

Use type[] to say "an array where every element is type":

let prices: number[] = [175, 42];
prices.push(34); // Valid: prices.push("hello"); // Error: Type 'string' is not assignable to type 'number'

let fruits: string[] = ["apple", "orange"];
fruits.push("banana"); // Valid: fruits.push(true); // Error: Type 'boolean' is not assignable to type 'string'

There's an equivalent generic form, Array<number>, but number[] is the common style.

Mixed arrays need a union

To allow more than one element type, use a union in parentheses:

let mixed: (number | string)[] = [1, "two"];
mixed.push(3); // Valid: mixed.push(true); // Error: 'boolean' is not assignable to 'number | string'

Gotcha — the empty array trap

An array literal with no explicit type and no elements is inferred as never[] (or any[] in loose mode) — TypeScript has nothing to infer from, so it assumes it stays empty. Always annotate empty arrays.

let numbers = [];        // inferred any[] — no safety
numbers.push(10); // allowed, but you lost type checking

let scores: number[] = []; // Valid: explicit — now push is checked
scores.push(10); // Valid: scores.push("text"); // Error: caught

Inference works from what's already in the array. Start empty and you start blind — annotate the element type up front.