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
最後に、アンダースコアや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!");
});
}