Tuples

A tuple type is a sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.

Cheatsheet

//          โ•ญโ”€โ”€ โญ๏ธ tuple โ”€โ”€โ•ฎ
type Pair = [string, number];

function f(pair: Pair) {
  const a = pair[0];          // โญ๏ธ access elements by index
  const b = pair[1];
}

function f(pair: Pair) {
  const [a, b] = pair;        // โญ๏ธ by array destructuring
}
 
f(["hello", 42]);

Optional elements

Rest elements

  • Tuples can have rest elements, which have to be an array/tuple type.

  • A tuple with a rest element has no set โ€œlengthโ€ - it only has a set of well-known elements in different positions.

Tuples types can be used in rest parameters and arguments, so that the following:

is basically equivalent to:

Variadic Tuple Types

Labeled Tuple Elements

Last updated

Was this helpful?