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

  • can only come at the end

  • affect the type of length

// โญ๏ธ must be last            โ•ญโ”€ โญ๏ธ โ”€โ•ฎ
type Point = [number, number, number? ];
 
function f(point: Point) {
  const [x, y, z] = point;          // โญ๏ธ z: number | undefined
  console.log(`${point.length}`);   // โญ๏ธ length: 2 | 3
}

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.

// โญ๏ธ rest element         โ•ญโ”€ โญ๏ธ rest โ”€โ•ฎ
type T1 = [string, number, ...boolean[] ];

// โญ๏ธ TypeScript 4.0 ๆ–ฐๅŠŸ่ƒฝ๏ผš
// TS < 4.0 => T2 ๆœƒ็”ข็”Ÿ๏ผš"A rest element must be last in a tuple type"
type T2 = [string, ...boolean[], number];     // โญ๏ธ needn't be last

const a: T1 = ["hello", 1];
const b: T1 = ["beautiful", 2, true];
const c: T1 = ["world", 3, true, false, true, false, true];

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

// rest param โ†ด
//         โ•ญโ”€ โญ๏ธ โ”€โ•ฎ โ•ญโ”€โ”€ โญ๏ธ tuple with rest elem โ”€โ”€โ•ฎ
function f(...args: [string, number, ...boolean[]]) {
  const [name, version, ...input] = args;
  // ...โ•ฐโ”€โ”€โ”€โ”€ โญ๏ธ array destructuring โ”€โ”€โ”€โ•ฏ
}

is basically equivalent to:

function f(name: string, version: number, ...input: boolean[]) {
  // ...
}

Variadic Tuple Types

๐Ÿšง under construction ...

Labeled Tuple Elements

๐Ÿšง under construction ...

Last updated