🎯 学习目标

  • 理解元组的概念和特点
  • 掌握元组的定义和使用
  • 学会可选元素和剩余元素
  • 了解只读元组

📚 元组定义

元组(Tuple)是一种固定长度每个位置类型确定的数组。

// 定义元组:[string, number] 表示第一个是字符串,第二个是数字 let user: [string, number] = ['Alice', 25]; // 访问元素 console.log(user[0]); // Alice console.log(user[1]); // 25 // 元素类型必须匹配 let wrong: [string, number] = [25, 'Alice']; // Error: 类型不匹配
💡
元组 vs 数组

数组所有元素类型相同,长度可变;元组每个位置类型可以不同,长度固定。

💻 元组操作

let tuple: [string, number, boolean] = ['hello', 42, true]; // 访问元素 let first: string = tuple[0]; // 'hello' let second: number = tuple[1]; // 42 let third: boolean = tuple[2]; // true // 解构赋值 let [str, num, bool] = tuple; // 长度固定 tuple[3]; // Error: 长度为 3 的元组没有索引 3 // 越界访问 tuple.push('extra'); // 允许,但不推荐
⚠️
越界元素

在严格模式下,向元组 push 元素会将其类型变为联合类型。建议避免这种操作。

🔧 可选元素

// 使用 ? 表示可选元素 let options: [string, number?] = ['hello']; options = ['world', 42]; // 也可以 // 可选元素必须放在最后 let tuple: [string, number?, boolean?]; tuple = ['a']; // OK tuple = ['a', 1]; // OK tuple = ['a', 1, true]; // OK

📊 剩余元素

// 使用 ... 表示剩余元素 let strings: [string, ...string[]] = ['first', 'second', 'third']; // 数字和字符串混合 let mixed: [number, ...string[]] = [1, 'a', 'b', 'c']; // 复杂示例 let complex: [string, number, ...boolean[]] = ['key', 42, true, false, true];

🔒 只读元组

// 使用 readonly 创建只读元组 let readonlyTuple: readonly [string, number] = ['Alice', 25]; // 不能修改 readonlyTuple[0] = 'Bob'; // Error: 无法修改 readonlyTuple.push(30); // Error: 类型 "readonly [string, number]" 上不存在属性 "push" // 函数参数中使用 function printTuple(tuple: readonly [string, number]) { console.log(`${tuple[0]}: ${tuple[1]}`); }

📝 本节小结

  • • 元组是固定长度、类型确定的数组
  • • 使用 [type1, type2, ...] 语法定义
  • • ? 表示可选元素,... 表示剩余元素
  • • readonly 创建不可变的只读元组