以下のように配列から型を自動的に生成することができます。
このようにしておくことで配列に変更があった時に型の修正の必要がありません。
const STATUS_VALUES = ["productInCart", "productInCheckout", "productPurchased"] as const;
type Status = typeof STATUS_VALUES[number]; // "productInCart" | "productInCheckout" | "productPurchased"
as constアサーション を行うと次のような制約をつけることができます。
1. 「値」や「配列やオブジェクトの全てのメンバ」が readonlyとなる。
2. Widening(型の拡大)がされない
const pikachu = {
name: "pikachu", // readonly
height: 0.4, // readonly
weight: 6.0, // readonly
} as const;
// string型
let hoge = "my-sample-text"
// "my-sample-text"型
let fuga = "my-sample-text" as const