as const はconst アサーションで、値を拡大せずに、最も具体的(リテラル)で深く readonly な型を推論するよう TypeScript に指示します。
ts
a = ;
obj = { : };
arr = [, ];
b = ;
obj2 = { : } ;
arr2 = [, ] ;
as const はconst アサーションで、値を拡大せずに、最も具体的(リテラル)で深く readonly な型を推論するよう TypeScript に指示します。
a = ;
obj = { : };
arr = [, ];
b = ;
obj2 = { : } ;
arr2 = [, ] ;
これは3つのことを行います。何も拡大しない(リテラル値を保持する)、すべてを readonly にする、そして配列をタプルに変換します。
値のリストからユニオン型を導出する(単一の信頼できる情報源):
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = typeof ROLES[number]; // "admin" | "editor" | "viewer"
// add a role to the array → the union updates automatically
設定や状態のリテラル型を保持する:
const action = { type: "INCREMENT", by: 1 } as const;
// action.type is "INCREMENT" (a literal), so it works in discriminated unions
// without as const it'd be `string`, breaking narrowing
as const は実行時の値と正確な型との橋渡しをします。
データを一度だけ定義し(配列やオブジェクト)、そこから正確なリテラル型を導出できます。これはアクションの型、ルートマップ、設定、そして string に拡大せずリテラルのままでなければならない判別ユニオンのタグにとって非常に貴重です。