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

See this reply of jcalz

Examples

  1. require same length of two tuples

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 that number is a subtype of T["length"] -> T has 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;
}

Tuple Examples

  • Tuple to Union

    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 TwitterImprove this article: Edit on GitHub

Discussion


Explain Programming

André Kovac builds products, creates software, teaches coding, communicates science and speaks at events.