键入 N 个数字的元组,后跟单个字符串

Typing a tuple of N numbers followed by a single string

考虑如下数组类型:

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]
             ...

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

是的,您可以输入以下内容,但只能在 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,但那时,rest 元素仅限于元组的末尾。所以你可以 [string, ...number[]],但不能 [...number[], string]

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.