Allen Yu Allen Yu
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
  • 开始

  • 基础

  • 进阶

    • 类型别名
    • 字符串字面量类型
    • 元组
      • 元组 (Tuple)
      • 简单的例子
      • 越界的元素
      • 类型转换
      • 参考
    • 枚举
    • 类
    • 类与接口
    • 泛型
    • 声明合并
    • 工具类型
    • 编译配置
  • 实战

  • TypeScript
  • 进阶
2020-10-31
目录

元组

# 元组 (Tuple)

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

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

# 简单的例子

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

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

访问索引的元素时,会得到正确的类型:

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

也可以只赋值其中一项

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

但是当对元组对象进行初始化或者赋值值,需要提供元组类型中,指定的所有项

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

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

# 越界的元素

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

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

tom.push('Jack')
tom.push(true)

// 类型“true”的参数不能赋给类型“string | number”的参数。ts(2345)

# 类型转换

如何把元组类型元素提取出来变成联合类型呢?

interface Animal {
  name: string
  age: number
}
type Tuple = [number, string, boolean, Animal]

type Union = Tuple[number]

// 相当于
type Union = string | number | boolean | Animal

# 参考

  • TypeScript 入门教程 - 元组 (opens new window)
Last Updated: 3/30/2022, 1:20:25 AM
字符串字面量类型
枚举

← 字符串字面量类型 枚举→

最近更新
01
4 月第 2 周总结
04-17
02
工具类型
04-01
03
Google 搜索小技巧
03-28
更多文章>
Theme by Vdoing | Copyright © 2018-2022 Allen Yu
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式