TypeScript の ThisType ユーティリティ
レベル 5437 打鍵
ThisType<D & M> はオブジェクトリテラルのメソッド内での this の型を TypeScript に伝えるので、メソッドは data の this.count を使えます。noImplicitThis オプション(strict に含まれる)が必要です。
TypeScript のコード
// データ部分 D とメソッド部分 M を持つ記述子1type ObjectDescriptor<D, M> = {2 data?: D; // これらのメソッドの中では this の型が D & M になる3 methods?: M & ThisType<D & M>;4};// D と M は渡されたオブジェクトから推論される5function createObject<D, M>(desc: ObjectDescriptor<D, M>): D & M { // 部分がなければ空のオブジェクトを使う6 const data = desc.data || {};7 const methods = desc.methods || {}; // data とメソッドを1つのオブジェクトにまとめるので、実行時にも this.count が使える8 return { ...data, ...methods } as D & M;9}10const counter = createObject({ // D は { count: number } と推論される11 data: { count: 0 },12 methods: { // ThisType のおかげで this.count が number だと分かる13 increment() { this.count++; },14 print() { console.log(`Count: ${this.count}`); }15 }16});// count が 0 から 1 になる17counter.increment();// 「Count: 1」を表示する18counter.print();実行結果
Count: 1
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
.× 13;× 11{× 11}× 11:× 8(× 7)× 7,× 6&× 4<× 4