我有一个接受2到4个参数的方法:
myMethod(a: string, b: string, c?: any, d?: number);在单元测试中,我尝试以这种方式向方法传递参数:
const args: [string, string, any, number] = ['a', 'b', 'c', 0];
myMethod(...args);即使我将args声明为设置长度,TypeScript编译器也会显示此错误:
TS2556:预期的2-4参数,但得到0或更多.
为什么会显示此错误?我能做些什么来保持最后一行(函数调用)的原样吗?
发布于 2018-06-25 00:02:59
请注意,此问题不再发生在TS3.0+中,请参阅操场链接。先前的答复:
这是一个已知问题,简单地回答了为什么会发生这种情况,TypeScript中的rest/spread支持最初是为数组而不是元组设计的。
您可以等待静息/展开位置的元组在TypeScript中得到支持;据推测,它将在TypeScript 3.0中引入,很快就会发布。
在那之前,你唯一的选择就是解决办法。您可以放弃扩展语法,逐个传递参数:
myMethod(args[0], args[1], args[2], args[3]); // type safe but not generalizable或者断言您的方法接受...args: any[],如下所示:
(myMethod as (...args:any[])=>void)(...args); // no error, not type safe或者忽略错误,
// @ts-ignore
myMethod(...args); // no error, not type safe编辑:或者使用不-目前-打得好 apply()方法(与前两个解决方案不同,它更改了发出的js):
myMethod.apply(this, args); // no error, not type safe所有这些都不是很好,所以如果等待该特性的实现是一个选项,您可能希望这样做。祝好运!
https://stackoverflow.com/questions/51014836
复制相似问题