web:ts元组
简介
元组(Tuple)是 TypeScript 中一个非常重要的概念,特殊的数组,它允许在数组中存储不同类型的元素,与普通数组不同,元组中的每个元素都有明确的类型和位置。元组可以在很多场景下用于表示固定长度、且各元素类型已知的数据结构。
语法格式
let tuple: [类型1, 类型2, 类型3, ...];用法示例
基础用法
// 声明元组类型
let person: [string, number]; // 初始化(必须完全匹配类型和长度)
person = ["Alice", 30]; // ✅ 正确
person = [30, "Alice"]; // ❌ 错误:类型顺序不匹配
person = ["Bob"]; // ❌ 错误:长度不足可选元素(?)
type Color = [number, number, number, number?]; // 最后一个元素可选
const rgba: Color = [255, 0, 0]; // ✅ 允许省略第4个元素(alpha)
const rgba2: Color = [255, 0, 0, 1]; // ✅剩余元素(Rest Elements)
type StringNumberPairs = [string, ...number[]];
const data: StringNumberPairs = ["ID", 1, 2, 3]; // ✅ 首个元素是string,其余是number只读元组(Readonly)
const point: readonly [number, number] = [10, 20];
point[0] = 5; // ❌ 错误:无法修改只读元组命名标签(TypeScript 4.0+)
增强可读性:
type HttpStatus = [status: number, message: string];
const notFound: HttpStatus = [404, "Not Found"];元组 vs 数组
特性 | 元组 | 数组 |
|---|---|---|
元素类型 | 各位置类型独立 | 所有元素类型相同 |
长度 | 固定长度(除非使用 | 动态长度 |
类型推断 | 精确到具体位置类型 | 统一为单一类型(如 |
注意事项
越界访问:访问超出声明长度的元素会报错(除非使用 Rest 语法)。
可变操作:即使元组被声明为只读,仍可用
as断言修改(需谨慎):
const mutable = [10, 20] as [number, number];
mutable.push(30); // ⚠️ 运行时允许但破坏类型安全!