在 TypeScript 3.0 之前,确实没有什么比像您这样的联合更好的了。但随后引入了一系列相关的新功能,以更好地支持元组类型,特别是它们与函数参数列表的关系。由于函数支持最终的剩余参数将不定数量的参数的类型表示为数组,因此引入最终值是有意义的元组中的剩余元素将不定数量的元组元素的类型表示为数组。
嘿,事实上,您的用例在文档中作为示例明确提到:
例如,[number, ...string[]]
表示带有 a 的元组number
元素后跟任意数量的string
元素。
那么让我们尝试一下:
type MyArray = [number, ...string[]];
const okay0: MyArray = [0]; // okay
const okay1: MyArray = [1, "a"]; // okay
const okay2: MyArray = [2, "a", "b"]; // okay
const okay3: MyArray = [3, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; // okay
const bad0: MyArray = [0, "a", false]; // error!
// ~~~~ <-- boolean is not assignable to string
const bad1: MyArray = ["x", "y"]; // error!
// ~~~ <-- string is not assignable to number
const bad2: MyArray = []; // error!
// ~~~~ <--- property '0' is missing (i.e., bad2[0] is missing)
在我看来很好。希望有帮助;祝你好运!
链接到代码