最佳答案
在TypeScript中,我可以将函数的参数声明为类型Function。是否有我缺少的“类型安全”方法?例如,考虑一下:
class Foo {save(callback: Function) : void {//Do the savevar result : number = 42; //We get a number from the save operation//Can I at compile-time ensure the callback accepts a single parameter of type number somehow?callback(result);}}
var foo = new Foo();var callback = (result: string) : void => {alert(result);}foo.save(callback);
保存回调不是类型安全的,我给它一个回调函数,其中函数的参数是一个字符串,但我传递了一个数字,并编译没有错误。我可以在保存类型安全函数中设置结果参数吗?
太长别读版本:TypeScript中是否有相当于. NET委托的版本?