LoginSignup
5
4

More than 3 years have passed since last update.

TypeScript の型の一部を変更する

Posted at

結論

こんな感じのを作ると良さそう(多分、組み込みには無いはず)。

type Replace<T, U> = {
  [P in keyof T]: P extends keyof U ? U[P] : T[P]
}

実例

リリース版の Nuxt Axios Module の retry の定義がおかしいので変更したかった(現在の dev ブランチでは修正済み)。

AxiosOptions {
  // これを boolean | IAxiosRetryConfig にしたい
  retry?: boolean
}

こんな感じでやろうとしたけどダメだった。

// こっちは OK
type CustomAxiosOptions = Omit<AxiosOptions, 'retry'> & { retry?: boolean | IAxiosRetryConfig }

// Configuration が extends Record<string, any> しているので、Omit が期待した結果にならない
type CustomConfiguration = Omit<Configuration, 'axios'> & { axios?: CustomAxiosOptions }

こんな感じにしたら期待通りの結果になった。

type Replace<T, U> = {
  [P in keyof T]: P extends keyof U ? U[P] : T[P]
}

type CustomAxiosOptions = Replace<AxiosOptions, { retry?: boolean | IAxiosRetryConfig }>
type CustomConfiguration = Replace<Configuration, { axios?: CustomAxiosOptions }>
5
4
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
5
4