TypeScript Arrays and Tuples
TypeScript arrays hold many values of the same type, while TypeScript tuples hold a fixed number of values where each position has its own type. Both are regular JavaScript arrays at runtime.
Typed Arrays
Write the element type followed by [], or use the generic form Array<T>. Both mean the same thing.
const scores: number[] = [88, 92, 75];
const names: Array<string> = ["Ali", "Hina"];
scores.push(99);
// scores.push("100"); // Error: 'string' is not assignable to 'number'.
console.log(scores.reduce((a, b) => a + b) / scores.length);88.5
Arrays of Objects and Mixed Types
Use parentheses around a union so the [] applies to the whole union.
const products: { name: string; price: number }[] = [
{ name: "Tea", price: 6 },
{ name: "Honey", price: 11.5 },
];
const ids: (number | string)[] = [1, "A-2", 3];
console.log(products.map((p) => p.name).join(", "), ids.length);Tea, Honey 3
Readonly Arrays
readonly arrays prevent push, pop, splice and index assignment. They are perfect for function parameters you promise not to change.
function total(prices: readonly number[]): number {
// prices.push(1); // Error: Property 'push' does not exist on type 'readonly number[]'.
return prices.reduce((a, b) => a + b, 0);
}
console.log(total([5, 10, 15]));30
Tuples
A tuple type lists the type of each position. Tuples are common for returning multiple values from a function, like React's useState. You can name elements for readability and mark them optional with ?.
let point: [number, number] = [10, 20];
type HttpResult = [status: number, body: string, cached?: boolean];
function fetchFake(): HttpResult {
return [200, "OK"];
}
const [status, body, cached = false] = fetchFake();
console.log(point[0] + point[1], status, body, cached);
// point = [1, 2, 3]; // Error: Source has 3 element(s) but target allows only 2.30 200 OK false
as const
Adding as const to an array literal makes it a readonly tuple of literal values. This is useful for fixed lists of options.
const sizes = ["S", "M", "L"] as const;
type Size = (typeof sizes)[number]; // "S" | "M" | "L"
const pick: Size = "M";
console.log(pick, sizes.length);M 3
Frequently asked questions
What is the difference between number[] and Array<number>?
Nothing. They are two syntaxes for the same type. number[] is shorter and more common; Array<T> can read better with complex element types.
What is a tuple in TypeScript?
A fixed-length array type where each position has a known type, like [string, number]. At runtime it is a normal array.
How do I declare an empty array with a type?
Annotate it: const list: string[] = []. Without the annotation, TypeScript may infer any[] or never[].