TypeScript 入门教程
  • TypeScript 入门教程
  • 进阶
    • 类与接口
    • 类
    • 声明合并
    • 装饰器
    • 枚举
    • 扩展阅读
    • 泛型
    • 字符串字面量类型
    • 元组
    • 类型别名
  • 基础
    • 任意值
    • 内置对象
    • 声明文件
    • 原始数据类型
    • 类型断言
    • 类型推论
    • 数组的类型
    • 函数的类型
    • 对象的类型——接口
    • 联合类型
  • 工程
    • 编译选项
    • 代码检查
  • 简介
    • 安装 TypeScript
    • Hello TypeScript
    • 什么是 TypeScript
    • why-typescript
  • 感谢
Powered by GitBook
On this page
  • 简单的例子
  • 越界的元素
  • 参考

Was this helpful?

  1. 进阶

元组

数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。

元组起源于函数编程语言(如 F#),这些语言中会频繁使用元组。

简单的例子

定义一对值分别为 string 和 number 的元组:

let tom: [string, number] = ['Tom', 25];

当赋值或访问一个已知索引的元素时,会得到正确的类型:

let tom: [string, number];
tom[0] = 'Tom';
tom[1] = 25;

tom[0].slice(1);
tom[1].toFixed(2);

也可以只赋值其中一项:

let tom: [string, number];
tom[0] = 'Tom';

但是当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。

let tom: [string, number];
tom = ['Tom', 25];
let tom: [string, number];
tom = ['Tom'];

// Property '1' is missing in type '[string]' but required in type '[string, number]'.

越界的元素

当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型:

let tom: [string, number];
tom = ['Tom', 25];
tom.push('male');
tom.push(true);

// Argument of type 'true' is not assignable to parameter of type 'string | number'.

参考

Previous字符串字面量类型Next类型别名

Last updated 4 years ago

Was this helpful?

()

Basic Types # Tuple
中文版