1

Looking at this simple code from MDN :

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

— I get an error :

enter image description here

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.

2
  • I have run into the same issue before. myFunction.apply(null, args) works. Commented Jun 21, 2017 at 17:00
  • Is that the exact code for myFunction? Are you sure that x, y, z don't have types? Commented Jun 21, 2017 at 17:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

But I'm passing an array which is explicitly any[3]
... and? It's still an array (okay, an array of three elements, but still an array) being passed to a function that takes three separate, required, arguments.
I might be missing something but that's the job of ...args. to "break" the array of [0,1,2] into 0,1,2. So things should be fine , no? myfunction will still get what it expectes : 3 values not as an array - but as simple arguments. just like with .apply
@Royi your understanding is correct: what's unclear here is how to get the TypeScript compiler to understand that and underscores the difficulty of layering types on top of extremely dynamic language features.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.