Typescript tuples
💻Programming Language
javascript
typescript
Tuple
- A tuple is a fixed-size list of elements of (different) types, e.g.
[string, number]
Giving the TS compiler hints
You need to give a hint to the compiler to expect a tuple type. Otherwise the compiler will widen an array literal like [2, 3, 4] to number[]. The hint usually takes the form of including a tuple type in the type annotation or generic constraint; preferably a union of some tuple type that doesn’t get in the way of what you’re doing
Examples
Here the compiler gets the hint readonly [] | -> a union with an empty tuple (the readonly just makes it more general)
function requireTwoSameLengthTuples<
T extends (readonly [] | readonly any[]) & (
number extends T["length"] ? readonly [] : unknown
)>(t: T, u: { [K in keyof T]: any }): void { }Other Notes:
number extends T["length"]means thatnumberis a subtype ofT["length"]->Thas to be an array in this case. I.e.T["length"]is not a numeric literal.| [never]hint
function myFunction<N extends number>(
array1: ArrayOfFixedLength<any, N> | [never],
array2: ArrayOfFixedLength<any, N & {}> | [never]) {
return true;
}- see discussion “Add a way to prefer narrowing array to tuple if possible”
- See
& {}discussion in the main TypeScript document
Tuple Examples
-
export type TupleToUnion<T extends unknown[]> = T[number]; export type TupleToUnion2<T extends unknown[]> = T extends [ infer U, ...infer Rest ] ? TupleToUnion2<Rest> | U : never;
Discuss on Twitter ● Improve this article: Edit on GitHub