mcpField
C
callback-this-type

callback-this-type

github.com/marius-townhouse開発644 回インストール38 週間前に更新
リポジトリ

callback-this-type について

コールバック API を定義するライブラリ作者や開発者向けの TypeScript スキルです。コールバックの `this` コンテキストを型付きの第1引数として宣言し、期待されるコンテキストを文書化してツールで補完できるようにします。

主な機能

  1. 01コールバックの `this` コンテキストの型付け
  2. 02コールバック API の期待値の明示
  3. 03コンテキストに応じた補完

活用シーン

  1. 01イベントハンドラーのコールバック型の定義
  2. 02ライブラリが `this` を設定するコールバックの型付け
  3. 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 が含まれる場合は、型を指定します

コメント