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