Tuples
TypeScript โฉ
Variadic Tuple Types (โณ๏ธ TS 4.0)
Labeled Tuple Elements (โณ๏ธ TS 4.0)
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]);
// โญ๏ธ 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 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];
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
Was this helpful?