TypeScript の ThisParameterType ユーティリティ型
レベル 4268 打鍵
ThisParameterType ユーティリティ型は関数からthisパラメータの型を抽出します。
TypeScript のコード
// カウンターとメソッドを持つオブジェクトのインターフェース1interface Counter {2 count: number; // this: Counter はメソッド内のthisの型を宣言する(実際の引数ではない)3 increment(this: Counter): void;4}// ThisParameterType でそのthisの型を取り出す(CounterThisはCounter)5type CounterThis = ThisParameterType<Counter["increment"]>;// 0から始まるCounterの実装オブジェクト6const counter: Counter = {7 count: 0,8 increment() { // thisはcounterオブジェクトなので、そのcountが1増える9 this.count++;10 }11};// incrementを2回呼ぶ(countは0 → 1 → 2)12counter.increment();13counter.increment();// 「2」と表示する14console.log(counter.count);実行結果
2
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
;× 8:× 5.× 5(× 5)× 5{× 3}× 3"× 2+× 2=× 2