callback-this-type について
コールバック API を定義するライブラリ作者や開発者向けの TypeScript スキルです。コールバックの `this` コンテキストを型付きの第1引数として宣言し、期待されるコンテキストを文書化してツールで補完できるようにします。
主な機能
- 01コールバックの `this` コンテキストの型付け
- 02コールバック API の期待値の明示
- 03コンテキストに応じた補完
活用シーン
- 01イベントハンドラーのコールバック型の定義
- 02ライブラリが `this` を設定するコールバックの型付け
- 03API 利用者向けのコールバックコンテキストの文書化
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ marius-townhouse/ effective-typescript-skills --skill callback-this-typeインストール後、Claude Code で/callback-this-typeを入力して読み込まれたか確認します。
詳細
コールバックの API に this が含まれる場合は、型を指定します
概要
ライブラリが特定の this コンテキストでユーザー提供のコールバックを呼び出す場合、そのコンテキストは API の一部です。TypeScript では、実際の引数ではありませんが、関数の最初のパラメーターとして this の型を指定できます。これにより、期待されるコンテキストをドキュメント化し、適用できます。
このスキルを使う場面
- コールバックで
thisを使用する - API が
thisコンテキストを提供する - イベントハンドラーに型を付ける
- ライブラリがコールバック内の
thisを設定する - コールバックのコンテキストをドキュメント化する
絶対ルール
コールバック API の一部である場合は、最初のパラメーターとして this の型を指定します。これにより、期待されるコンテキストがドキュメント化され、オートコンプリートが有効になります。
例
// BAD: this is untyped
interface EventEmitter {
on(event: string, handler: (data: any) => void): void;
}
// User doesn't know what 'this' is:
emitter.on('click', function(data) {
this.something; // What properties does this have?
});
// GOOD: this is typed
interface EventEmitter {
on(
event: string,
handler: (this: EventContext, data: any) => void
): void;
}
interface EventContext {
target: Element;
timestamp: number;
preventDefault(): void;
}
// User now gets autocompletion for 'this'
emitter.on('click', function(data) {
this.target; // Autocomplete works!
this.timestamp; // Typed as number
});
参考資料
- Dan Vanderkam 著『Effective TypeScript』第 2 版
- 項目 69:コールバックの API に
thisが含まれる場合は、型を指定します
コメント
Markdown 対応