LoginSignup
2
1

More than 3 years have passed since last update.

declare moduleで型を拡張するときのtsconfigの設定

Posted at

問題点

vuexのように既存の型が貧弱なライブラリではユーザーが型定義ファイル(d.ts)を用いて型を拡張することができます。

type/vuex.d.ts
declare module 'vuex' {
  type Getters<S, G> = {
    [K in keyof G]: (
      state: S,
      getters: G,
      rootState: RootState,
      rootGetters: RootGetters
    ) => G[K]
  }
...
}

そしてこのvuexを使おうとしたところ

import { Getters } from 'vuex'
//       ~~~~~~~ Module '"vuex/types/index"' has no exported member 'Getters'. Did you mean 'Getter'?ts(2724)

と怒られた。
この時vuexはmodule "node_modules/vuex/types/index"とmode_moduleの方しか見ていなかった。

vuexをインポートするときにtype/vuex.d.tsを見てくれるようにしたい

解決

tsconfigでインポートするときに見るパスを直接指定する方法がある。
pathsオプションに以下のようにパスを指定した。

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "vuex": ["src/types/vuex.d.ts"]
    },
  }
}

baseUrlを指定し、そこからのパスを設定したらうまく読み込むようになった。

2
1
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
2
1