Spread语法和Typescript提供的参数不匹配? [英] Spread syntax and Typescript — supplied parameters do not match?
问题描述
查看
即使我很清楚:
function myFunction(x,y,z):void {}
var args:any [3] = [0,1,2];
myFunction(... args:any [3]);
仍然无效。
问题:
为什么它不起作用,我错过了什么?
我已经看到这个答案,它使错误通过:
function myFunction(x,y,z):void {}
var args = [0,1 ,2];
(< any> myFunction)(... args);
为什么< any>
错误?
如果是这样的话,这将是清楚的:
(< any>)(myFunction(... args)) ;
但不是。
就像TypeScript一样,你传递一个数组到一个需要三个参数的函数。因此签名失配错误。
让我在这里清楚一点:你所拥有的绝对有效 ES2015 JavaScript。这只是无效的TypeScript。
(< any> myFunction)
casts myFunction
as,嗯,任何东西,所以TypeScript不看函数定义。 (&F)(myFunction(... args)); 会告诉编译器调用 myFunction
是任何
。
Looking at this simple code from MDN :
function myFunction(x, y, z):void { }
var args = [0, 1, 2];
myFunction(...args);
Even If I'm being super clear :
function myFunction(x, y, z):void { }
var args:any[3] = [0, 1, 2];
myFunction(...args:any[3]);
It still doesn't work.
Question:
Why doesn't it work and did I miss something ?
I've already seen this answer which muted the error via :
function myFunction(x, y, z):void { }
var args = [0, 1, 2];
(<any>myFunction)(...args);
Why did <any>
mute the error ?
It would've been clear if it was :
(<any>)(myFunction(...args));
but it's not.
As far as TypeScript is concerned, you're passing an array to a function that takes three arguments. Thus the signature mismatch error.
Let me be clear here: What you have is absolutely valid ES2015 JavaScript. It's just not valid TypeScript.
(<any>myFunction)
casts myFunction
as, well, "anything", so TypeScript doesn't look at the function definition. (<any>)(myFunction(...args));
would tell the compiler the result of calling myFunction
is any
.
这篇关于Spread语法和Typescript提供的参数不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!