编辑 2014-01-28:
新读者,请务必查看下方扎克的回答。
他有一个更简洁的解决方案,可以让您使用粗箭头语法在类定义中定义和实例化作用域函数。
我要补充的唯一一件事是,关于Zac 回答中的选项 5,可以使用以下语法指定方法签名和返回类型而无需任何重复:
public myMethod = (prop1: number): string => {
return 'asdf';
}
编辑 2013-05-28:
定义函数属性类型的语法已更改(自 TypeScript 0.8 版起)。
以前,您会像这样定义函数类型:
class Test {
removeRow: (): void;
}
现在已更改为:
class Test {
removeRow: () => void;
}
我已经更新了下面的答案以包含此新更改。
另外:如果您需要为相同的函数名称定义多个函数签名(例如运行时函数重载),那么您可以使用对象映射表示法(这在 jQuery 描述符文件中被广泛使用):
class Test {
removeRow: {
(): void;
(param: string): string;
};
}
您需要将签名定义为removeRow()
类的属性,但在构造函数中分配实现。
有几种不同的方法可以做到这一点。
选项1
class Test {
// Define the method signature here.
removeRow: () => void;
constructor (){
// Implement the method using the fat arrow syntax.
this.removeRow = () => {
// Perform your logic to remove the row.
// Reference `this` as needed.
}
}
}
如果你想让你的构造函数最小化,那么你可以removeRow
在类定义中保留方法,并在构造函数中分配一个代理函数:
选项 2
class Test {
// Again, define the method signature here.
removeRowProxy: () => void;
constructor (){
// Assign the method implementation here.
this.removeRowProxy = () => {
this.removeRow.apply(this, arguments);
}
}
removeRow(): void {
// ... removeRow logic here.
}
}
选项 3
最后,如果您使用像 underscore 或 jQuery 这样的库,那么您可以使用它们的实用程序方法来创建代理:
class Test {
// Define the method signature here.
removeRowProxy: () => void;
constructor (){
// Use jQuery to bind removeRow to this instance.
this.removeRowProxy = $.proxy(this.removeRow, this);
}
removeRow(): void {
// ... removeRow logic here.
}
}
然后你可以deleteItem
稍微整理一下你的方法:
// Specify `Function` as the callback type.
// NOTE: You can define a specific signature if needed.
deleteItem(removeRowCallback: Function ): void {
$.ajax(action, {
data: { "id": id },
type: "POST"
})
// Pass the callback here.
//
// You don't need the fat arrow syntax here
// because the callback has already been bound
// to the correct scope.
.done(removeRowCallback)
.fail(() => {
alert("There was an error!");
});
}