在TypeScript中,我可以将函数的参数声明为Function类型。有没有一种“类型安全”的做法,我失踪了?例如,考虑一下:在TypeScript中可以使用强类型函数作为参数吗?
class Foo {
save(callback: Function) : void {
//Do the save
var 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);
保存回调不是类型安全的,我给它一个回调函数,其中该函数的参数是一个字符串,但我传递了一个数字,并没有错误编译。我可以使结果参数保存为类型安全函数吗?
tl; dr版本:是否有相当于TypeScript中的.NET代理?
呵呵,现在看起来很明显。谢谢! – vcsjones
'''(n:number)=> any'''表示任何函数签名? –
@nikkwong它意味着函数带有一个参数('数字'),但返回类型根本不受限制(可以是任何值,甚至是'void') –