【问题标题】:how to limit array's type in specific order in typescript如何在打字稿中以特定顺序限制数组类型
【发布时间】:2018-10-04 04:26:13
【问题描述】:

如何在打字稿中以特定顺序限制数组的类型,而不是定义范式。

这意味着,在 ts 中,我们只需声明一个数组定义,如下所示:

const arr:Array<any> = []

我想在定义数组中得到一个特定的顺序,比如:

const arr = ['string', 0, ...];

value只能是位置0的字符串tyoe,位置1只能是数字类型...

谢谢

【问题讨论】:

  • Typescript 的数组是同质的,所以你说的做不到。您可以为此目的使用一个对象。
  • 我参考了prosemirror-model的定义,就是这样用的,谢谢

标签: arrays typescript definitions


【解决方案1】:

如果您想将大小限制为 2 个元素,您可以使用 tuple 实现此目的

const myTuple: [string, number] = ['test', 3]

或将元组类型定义提取到一个类型中

type myTupleType = [string, number]
const myTuple2: myTupleType = ['test', 3]

【讨论】:

    【解决方案2】:

    可以用交集类型来完成:

    type OrderedArray<T> = Array<T> & {
        0?: string;
        1?: number;
    }
    
    const arr: OrderedArray<any> = ['string', 0, ...];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多