在 TypeScript 中,我可以将函数的参数声明为 Function 类型。是否有我缺少的“类型安全”方法?例如,考虑一下:
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 委托(delegate)?
最佳答案
当然。函数的 type由其参数类型和返回类型组成。这里我们指定 callback
参数的类型必须是“接受数字并返回类型 any
的函数”:
class Foo {
save(callback: (n: number) => any) : void {
callback(42);
}
}
var foo = new Foo();
var strCallback = (result: string) : void => {
alert(result);
}
var numCallback = (result: number) : void => {
alert(result.toString());
}
foo.save(strCallback); // not OK
foo.save(numCallback); // OK
如果你愿意,你可以定义一个type alias封装这个:
type NumberCallback = (n: number) => any;
class Foo {
// Equivalent
save(callback: NumberCallback) : void {
callback(42);
}
}
关于typescript - TypeScript 中是否可以使用强类型函数作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638990/