【TypeScript】オブジェクトのプロパティの値をUnion型で表現する

2022/12/03に公開
const Weather = {
  Sunny: "sunny",
  Rainy: "rainy",
  Clowdy: "clowdy",
} as const;

上記のようなオブジェクトが存在する場合

type Weather = typeof Weather[keyof typeof Weather];
// sunny | rainy | clowdy

このようにすることで、オブジェクトのキーだけを選択肢としたUnion型を作成することができます。
こちらを分解して解釈していきます。

keyof typeof Weather
//"Sunny" | "Rainy" | "Clowdy"

typeof A は A というオブジェクトの型、 keyof A はオブジェクトのキーを選択肢としたユニオン型になりますので「WeatherのキーのUnion型」が形成されます。

type Weather = typeof Weather["Sunny" | "Rainy" | "Clowdy"]

先ほどのkeyof typeof Weatherを置き換えると

type Weather = 
  typeof Weather["Sunny"] | 
 typeof Weather["Rainy"] | 
 typeof Weather["Clowdy"]

上記のような、それぞれのプロパティーの値をとったユニオン型が完成します。

const アサーション

https://typescriptbook.jp/reference/values-types-variables/const-assertion

as constを指定したオブジェクトは全てのプロパティがreadonlyのプロパティとなり、代入不可かつコンストで指定した値がそのプロパティの型になります。

Discussion