配列の値(as const)からUnion型(合併型)を生成する

● 配列の値(as const)からUnion型(合併型)を生成する

以下のように配列から型を自動的に生成することができます。
このようにしておくことで配列に変更があった時に型の修正の必要がありません。

const STATUS_VALUES = ["productInCart", "productInCheckout", "productPurchased"] as const;
type Status = typeof STATUS_VALUES[number];    // "productInCart" | "productInCheckout" | "productPurchased"

● as const についておさらい

as constアサーション を行うと次のような制約をつけることができます。

1. 「値」や「配列やオブジェクトの全てのメンバ」が readonlyとなる。
2. Widening(型の拡大)がされない

・ 1. 「値」や「配列やオブジェクトの全てのメンバ」が readonlyとなる。

const pikachu = {
  name: "pikachu",    // readonly
  height: 0.4,    // readonly
  weight: 6.0,    // readonly
} as const;

・ 2. Widening(型の拡大)がされない

// string型
let hoge = "my-sample-text"

// "my-sample-text"型
let fuga = "my-sample-text" as const
No.2392
09/13 15:11

edit