Z
ZHANK
高级类型

元组 (Tuple)

掌握定长定类型数组、具名元组、可变元组

元组 (Tuple)

元组是固定长度、固定类型的数组。

学完本章你将: 掌握元组定义、具名元组、可变元组。


基本元组

typescript
// 定长定类型
let pair: [string, number] = ["hello", 42];

// 解构
const [word, count] = pair;
console.log(word);   // "hello"(string)
console.log(count);  // 42(number)

// 实战:坐标
type Point2D = [number, number];
type Point3D = [number, number, number];

const p2: Point2D = [10, 20];
const p3: Point3D = [10, 20, 30];

可变元组

typescript
// 前两个固定,后面任意数量
type StringTuple = [string, string, ...string[]];

const a: StringTuple = ["a", "b"];
const b: StringTuple = ["a", "b", "c", "d"];

// 展开
type Concat<T extends unknown[], U extends unknown[]> = [...T, ...U];
type Result = Concat<[1, 2], ["a", "b"]>; // [1, 2, "a", "b"]

具名元组

typescript
// 给每个位置加标签(TS 4.0+)
type HttpHeader = [name: string, value: string];

const header: HttpHeader = ["Content-Type", "application/json"];

// 标签不影响类型,只用于 IDE 提示
const [headerName, headerValue] = header;

实战场景

typescript
// React useState 返回的就是元组
function useState<T>(initial: T): [T, (val: T) => void] {
    let state = initial;
    return [state, (val) => { state = val; }];
}

// CSV 行
type CsvRow = [string, number, string]; // [name, age, city]
const row: CsvRow = ["Alice", 25, "北京"];

// 函数参数展开
function draw(...args: [x: number, y: number, color?: string]): void {
    const [x, y, color = "black"] = args;
    console.log(`绘制于 (${x}, ${y}),颜色:${color}`);
}
draw(10, 20, "red");