LoginSignup
2
3

More than 5 years have passed since last update.

TypeScriptで型のキーの名前だけを入れ替える

Posted at

やりたいこと

type Person = {
  name: string;
  age: number;
  job?: string;
}

type EnhancedPerson = Swap<Person, 'name', 'fullname'>

/*
EnhancedPerson = {
  fullname: string;
  age: number;
  job?: string;
}
*/

やったこと

  • (recomposeとかからOmitをインポート。)
  • 引数はもとの型Tと、Tの任意のキー名Aと、Aと入れ替えたい任意のキー名Bの3つ。
  • Omit<T, A>でもとの型の任意のプロパティAを省く。
  • { [P in B]: T[A] }Bのキーに対してAが持っていたバリューを割り当てた型を作ってそれをインターセクション
type Swap<T, A extends keyof T, B extends string> = Omit<T, A> & { [P in B]: T[A] }

結果

多分できた。他に誰かもっと効率よいやつを作っていそう。

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