Typescript and spread operator?

前端 未结 3 963
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 07:43
function foo(x:number, y:number, z:number) { 
   console.log(x,y,z);
}
var args:number[] = [0, 1, 2];

foo(...args);

Why am i getting getting this

3条回答
  •  粉色の甜心
    2020-12-09 08:02

    So there is a little clause you may have missed:

    Type checking requires spread elements to match up with a rest parameter.

    Without Rest Paramater

    But you can use a type assertion to go dynamic... and it will convert back to ES5 / ES3 for you:

    function foo(x:number, y:number, z:number) { 
     console.log(x,y,z);
    }
    var args:number[] = [0, 1, 2];
    
    (foo)(...args);
    

    This results in the same apply function call that you'd expect:

    function foo(x, y, z) {
        console.log(x, y, z);
    }
    var args = [0, 1, 2];
    foo.apply(void 0, args);
    

    With Rest Parameter

    The alternative is that it all works just as you expect if the function accepts a rest parameter.

    function foo(...x: number[]) { 
     console.log(JSON.stringify(x));
    }
    var args:number[] = [0, 1, 2];
    
    foo(...args);
    

提交回复
热议问题