as const してから typeof arrnumber でUnion型にする code:ts
type Role = typeof ROLESnumber; // 'admin' | 'editor' | 'viewer'
code:使用例.ts
function canEdit(role: Role) {
return role === 'admin' || role === 'editor';
}
canEdit('admin'); // ✅ OK
canEdit('viewer'); // ✅ OK
canEdit('guest'); // ❌ エラー: 'guest' は Roleに含まれない
code:ts
const x = 'admin'; // 型: string
const y = 'admin' as const; // 型: 'admin'
上の例ROLESの値から型を取り出す
2. typeof
typeof ROLES → readonly ["admin","editor","viewer"]
配列の要素から Union型を生成したい。そこで次のようにする
3. [number] (インデックス型アクセス)で配列やタプルの「要素の型」を取り出す
typeof ROLES[number] → 'admin' | 'editor' | 'viewer'
literal type inferenceとindexed access typesの組み合わせ