为什么TypeScript抱怨数组长度?

Bee*_*ice 2 types typescript

我有一个接受2到4个参数的方法:

myMethod(a: string, b: string, c?: any, d?: number);
Run Code Online (Sandbox Code Playgroud)

在单元测试中,我尝试以这种方式将参数传递给方法:

const args: [string, string, any, number] = ['a', 'b', 'c', 0];
myMethod(...args);
Run Code Online (Sandbox Code Playgroud)

即使我声明args为设定长度,TypeScript编译器也会显示以下错误:

TS2556:预期2-4个参数,但得到0或更多.

为什么会显示此错误?有什么办法可以保留最后一行(函数调用)吗?

jca*_*alz 5

这是一个众所周知的问题,为什么它发生的简短答案是TypeScript中的rest/spread支持最初是为数组而不是元组设计的.

您可以在TypeScript中支持休息/展开位置中的元组 ; 它应该是从TypeScript 3.0开始引入的,它很快就会推出.

在此之前,您唯一的选择是解决方法.您可以放弃传播语法并逐个传递参数:

myMethod(args[0], args[1], args[2], args[3]);  // type safe but not generalizable
Run Code Online (Sandbox Code Playgroud)

或声明您的方法接受...args: any[]如下:

(myMethod as (...args:any[])=>void)(...args);  // no error, not type safe
Run Code Online (Sandbox Code Playgroud)

或忽略错误,

// @ts-ignore
myMethod(...args); // no error, not type safe
Run Code Online (Sandbox Code Playgroud)

编辑:或使用当前不良类型的 apply()方法(与前两个解决方法不同,更改发出的js):

myMethod.apply(this, args); // no error, not type safe
Run Code Online (Sandbox Code Playgroud)

这些都不是很好,所以如果等待实现该功能是一个你可能想要这样做的选项.祝好运!