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