Arrays and tuples — T[], readonly, and a tuple that push can still grow¶
Level: 101 · for JavaScript programmers writing their first types
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A tuple type is an array with a type per position, not a fixed-length array: pair.push(99) on a [string, number] compiles and makes length 3, yet tsc still rejects pair[2]; only readonly [string, number] refuses the push.
Keywords: tuple, ReadonlyArray, Array<T>
What the finished page will answer¶
- Why does
pair.push(99)compile on a[string, number], and what dopairandpair.lengthhold afterwards? - Why does tsc reject
pair[2]with TS2493 even after the push has made it exist? - What do
readonly string[],ReadonlyArray<string>andreadonly [string, number]remove from the type, and why can areadonly string[]not be passed where astring[]is expected (TS4104)? - What does
[1, "a"]infer, a tuple or(string | number)[], and what changes withas constor a tuple annotation? - What type does
lengthhave for[string, number?]and for[string, ...number[]]?
Examples it will need¶
-
arrays_and_tuples_push_sh.sh— tsc's TS2493 for a tuple read past its end and TS2339 for a readonly tuple push, then Node printing the grown tuple and its length 3 -
arrays_and_tuples_readonly_tserror.ts— TS4104 when areadonly string[]is passed to a function that takesstring[] -
arrays_and_tuples_lengths_tserror.ts— thelengthtypes of a fixed, an optional-element and a rest tuple, printed through deliberate TS2322 errors
See also¶
- Arrays — the run-time array that every tuple type describes
- Mutating and copying methods — the methods that a
readonlyarray type removes - Index access — why
arr[99]is typed as present - Destructuring — unpacking a tuple into named variables
- Rust: Tuples ↗ — a Rust tuple really does have a fixed length
- Rust: Array or
Vec? ↗ — fixed-size array or growable Vec, the choice TypeScript blurs