LoginSignup
1
0

More than 1 year has passed since last update.

Mapped Typesでオブジェクトのvalueの名前をkeyにしたい

Posted at

初めに

この記事は私のTypeScriptに関する備忘録をアウトプットするために使用をしています。
もっといいやり方があれば教えていただけると嬉しいです ( ´・‿・`)

こんなことがしたい

  • リテラルの型をkeyにする
  • それぞれのkeyに対して同じ型をつける

下記は例えが悪いので何でこんなことをしたいのだ?となるかもなのですがそこは無視してください..

type Servise = {
  online: 'オンライン';
  offLine: 'オフライン';
};

// ↓↓↓↓↓↓↓↓↓ 

type OutputServise = {
  オンライン: string[];
  オフライン: string[];
};

こうやって対応をした

type ValueOf<T> = T[keyof T];

type ValueOfKey<T extends string, K> = {
  [P in T]: K;
};

// 結果
// type OutputService = {
//     オンライン: string[];
//     オフライン: string[];
// }
type OutputService = ValueOfKey<ValueOf<Servise>, string[]>;

最後に

すごい細かい内容ではあるのですが、Mapped Typesを用いたアウトプットでした( ´・‿・`)

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