打字稿和传播运算符? [英] Typescript and spread operator?

查看:25
本文介绍了打字稿和传播运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

foo(...args);

为什么我在 Typescript Playground 中收到这个错误???

Why am i getting getting this error in Typescript Playground???

提供的参数与调用目标的任何签名都不匹配.

Supplied parameters donot match any signature of call target.

推荐答案

因此,您可能错过了一个小条款:

So there is a little clause you may have missed:

类型检查需要扩展元素与其余参数匹配.

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

无休息参数

但是你可以使用类型断言来动态...它会为你转换回 ES5/ES3:

Without Rest Parameter

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];

(<any>foo)(...args);

这会产生与您期望的相同的 apply 函数调用:

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);

带休息参数

另一种选择是,如果该函数接受一个 rest 参数,那么一切都如您所愿.

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);

这篇关于打字稿和传播运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆