【问题标题】:Typing a tuple of N numbers followed by a single string键入 N 个数字的元组,后跟单个字符串
【发布时间】:2021-10-22 06:37:45
【问题描述】:

考虑如下数组类型:

let example1: MyArray = ['John'],
    example2: MyArray = [4, 5, 1, 5, 'Eric'],
    example3: MyArray = [1, 5, 7, 3, 4, 5, 1, 'Joe'],
    ...

所以最后一个字符串和任意数量的数字。

到目前为止,我可以想象MyArray 类型(看起来像Death by a Thousand Overloads problem)的简单实现:

type MyArray = [string]
             | [number, string]
             | [number, number, string]
             | [number, number, number, string]
             | [number, number, number, number, string]
             ...

这显然不是最理想的。是否存在更好的方法?

【问题讨论】:

  • @Carcigenicate 当然可以,但是这样做可能会产生很多开销,这很可能是不必要的。如果键入正确,Typescript 可以非常安全地处理这个问题。

标签: typescript typescript-types


【解决方案1】:

是的,你可以输入这个,但只能在 Typescript 4.2 或更高版本中输入:Leading/Middle Rest Elements in Tuple Types

type MyArray = [...number[], string];

const example1: MyArray = ['John'],
      example2: MyArray = [4, 5, 1, 5, 'Eric'],
      example3: MyArray = [1, 5, 7, 3, 4, 5, 1, 'Joe'];

在此之前,3.0 引入了Rest elements in tuple types,但当时,其余元素仅限于元组末尾。所以你可以[string, ...number[]],但不能[...number[], string]

【讨论】:

  • 啊,你打败了我;您可能想要链接到 TS4.2 中引入的 leading/middle rest elements in tuple types 的文档
  • 谢谢!我在没有运气的情况下弄乱了传播运算符,但现在我很清楚了。
  • @jcalz 谢谢,我错过了 3.0 版本仅限于作为元组最后一部分的其余元素。
  • @KRyan 如果您能为我最初的问题想出一个更好的标题,请随时建议/更改它
  • @KRyan 只是为了澄清一下(现在我看到了新标题):这个问题的目的是解决一般问题 - 不是专门针对数字和字符串。
【解决方案2】:

Typescript 允许

type MyArray = [number, ...string[]]
const arr: MyArray = [12, 'wsd', 'qwdqwdqd', 'qwqdqdqdw'];

很遗憾,type MyArray = [...string[], number] 是不允许的。 TS 说A rest element must be last in a tuple type.

【讨论】:

  • 在 Typescript 4.2 之前都是如此。然而,现在我们可以这样做了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 2018-09-11
  • 2023-03-13
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多