【问题标题】:how to define an interface structure which is [string, number] - typescript tuples如何定义一个接口结构,它是 [string, number] - typescript tuples
【发布时间】:2021-03-05 18:50:51
【问题描述】:

我可以在 Typescript 中定义混合类型的数组内容吗?

我以二维数组的格式返回一些结果,例如:

[
  [ 'red', 0.1 ],
  [ 'blue', 0.2 ]
]

我想定义某种类型的内部结构,比如二元数组

interface Match {
  [string, number]
}

然后我以后的函数可以返回Promise<Match[]>

但不确定语法如何做到这一点。

即使我只是尝试最简单的语法,我也不知道如何定义一个混合两个项目的数组,

string[][]

可以为二维字符串数组找到,但由于这更像是一个元组,所以在数组中混合类型...

我想我可以放弃并使用更清晰的标签类型,例如

interface Match {
  tag: string
  conf: number
}

但创建对象似乎效率低下,因为我将拥有大量这些数据实例(内部机器学习数据结构)

想法?

我在 typescript 中找到了关于元组的页面,但不清楚如何使用它们导出接口。

https://www.tutorialsteacher.com/typescript/typescript-tuple

【问题讨论】:

    标签: arrays typescript tuples


    【解决方案1】:

    不要使用接口,只需使用专为此目的设计的type alias:

    type Match = [string, number];
    

    您的数组类型将是Match[]。如果没有类型别名,它只是[string, number][]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 2023-03-14
      • 2021-11-07
      • 2022-01-21
      • 2020-05-01
      • 1970-01-01
      • 2015-07-27
      相关资源
      最近更新 更多