Sub topic 5
Arrays and tuples
This chapter assumes you know basic TypeScript annotations, can run tsc or use a TypeScript-aware editor, and have read about union types. Arrays and tuples are the two main ways to type a list of values. An array holds any number of items that share one type. A tuple holds a fixed number of items, each with its own type.
Array types
You can write an array type in two equivalent ways: number[] or Array<number>. The first form is more common.
const scores: number[] = [90, 75, 88];
scores.push(100); // ok
// scores.push("A"); // Error: string is not assignable to numberWhen you leave out the annotation, TypeScript infers the type from the values. An array literal with mixed values gets a union element type:
const mixed = [1, "two"]; // inferred as (string | number)[]Indexing an array returns the element type, not undefined, unless you enable the noUncheckedIndexedAccess compiler option. Keep this in mind when you read past the end of an array.
Tuple types
A tuple is written as a bracketed list of types. Its length and the type at each position are fixed.
const pair: [string, number] = ["age", 30];
// const wrong: [string, number] = [30, "age"]; // Error: types in wrong order
// const short: [string, number] = ["age"]; // Error: missing elementWithout an annotation, an array literal is inferred as an array, not a tuple. This is a common source of errors:
const pair = ["age", 30]; // (string | number)[], not a tupleAdd the annotation when you need the tuple type. Labeled elements, optional elements, and rest elements make tuples more flexible:
type Range = [start: number, end: number];
type Point3 = [number, number, number?]; // third element optional
type Labeled = [string, ...string[]]; // one string, then any number more
function makeRange(start: number, end: number): Range {
return [start, end];
}
function sum(values: readonly number[]): number {
return values.reduce((total, v) => total + v, 0);
}
const [start, end] = makeRange(1, 5);
console.log(end - start); // 4
console.log(sum([1, 2, 3])); // 6The readonly modifier on values tells the compiler that sum will not change the array. A caller can then pass either a mutable or a readonly array.
flowchart TD
A[Value is a list] --> B{Same type for every item?}
B -- Yes --> C[Use T[] for an array]
B -- No --> D{Fixed length and position types?}
D -- Yes --> E[Use a tuple such as [string, number]]
D -- No --> F[Use a union array such as (string or number)[]]Choosing between them
Use an array when the length varies and every item has the same meaning. Use a tuple when position carries meaning, such as a coordinate pair or a function that returns two results. A tuple also stops you from reading or writing the wrong position.
> Note: a tuple's push method is still allowed by the compiler, which can let the length grow past the declared shape. Prefer readonly tuples when you want to prevent this.
Exercise
Exercise
What type does TypeScript infer for const p = [1, "a"];, and how do you make it a tuple of number and string?
Show answer
It infers (string | number)[]. Annotate it as const p: [number, string] = [1, "a"]; to make it a tuple.