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
}
/* -------- optional element -------- */
// ⭐️ 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];