LoginSignup
3
2

More than 3 years have passed since last update.

TypeScriptでthisの型を指定する方法

Posted at

さっそく結論ですが TypeScript のバージョン 2.3 から ThisType という組み込みの型が使えるためこれを利用します。

const obj: ThisType<{ name: string }> = {
  test() {
    return this.name; // 推論できる
  }
};

日常的にはあまり使われないかもしれませんが、ライブラリの型定義などであると便利な型です。

例えば Vue.js で TypeScript を用いる際、this の型が推論されるのはライブラリ内部で ThisType を用いて型定義が行われているおかげです。

ThisType が使われている箇所:vue/options.d.ts at 731e4d0ebc997a6c2b1fc500b08924ff7ba091b6 · vuejs/vue

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2