在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);
save回调不是类型安全的,我给它一个回调函数,其中函数的参数是一个字符串,但我传递给它一个数字,并且编译时没有错误。我可以在保存类型安全函数中设置结果参数吗?
TL;DR版本:在TypeScript中是否存在与.NET委托等价物?
当然可以。函数的类型由其参数类型和返回类型组成。在这里,我们指定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 NumberCallback = (n: number) => any;
class Foo {
// Equivalent
save(callback: NumberCallback) : void {
callback(42);
}
}