2016-12-14 111 views
3

使用VS17RC与TS 2.1使用的编译错误打字稿传播操作结果

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

给出了编译时错误“提供的参数不匹配,通话对象的任何签名。”

这是编译的JS:

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

这是实际可行的。

我在这里做错了吗?

的例子来自这里:Typescript Deep Dive

回答

1

这是我的解决方法是:

/** 
* Function definition 
*/ 
class SockService { 
    connect(...args:Array<string>) { 
    if (args.length > 1) { 
     [this.host, this.path] = args; 
    } 
    } 
} 

/** 
* Function usage 
*/ 
var endpoint = { 
    'local_test': [] as Array<string>, 
    'local': ['0.0.0.0:8080', '/foo/websocket'], 
    'production': ['192.0.2.1:8080', '/foo/websocket'] 
}; 

this.sock.connect(...endpoint.local_test); 

我不喜欢使用这样的休息参数,因为它使函数定义描述要少得多。但这是我得到扩展到在TypeScript中使用函数参数的唯一方法。