Published on

TypeScript - 元祖

Authors
  • avatar
    Name
    Deng Hua
    Twitter

目录

Introducing Tuples

Tuples are a special type exclusive to TypeScript (they don't exist in JS) Tuples are arrays of fixed lengths and ordered with specific types - like super rigid arrays.

元祖本质也是一个数组类型,但它是一个固定长度的数组,并且用一组固定的类型排序。

let myTuple: [string, number] = ['john', 1]

元祖对数组内类型的顺序也有严格要求

let myTuple: [string, number] = [1, 'john'] // ❌

不过在元祖中,你依旧可以使用数组的方法。

const myTuple: [string, number] = ['john', 1]

myTuple.push(2)