Spread syntax and Typescript — supplied parameters

2019-08-02 16:32发布

问题:

Looking at this simple code from MDN :

function myFunction(x, y, z):void { }
var args = [0, 1, 2];
myFunction(...args);

— I get an error :

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.

回答1:

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.