はじめに
例えば以下のように、Union Typeの定義とそれを扱う配列を定義したい場合、重複した内容を記述する必要がありました。
これを、3.4から導入されたconst assertionを使ってスッキリ書く方法を紹介します。
type fruitType = 'apple' | 'orange' | 'grape';
const fruits: fruitType[] = ['apple', 'orange', 'grape'];
Union Typeを配列のconst assertionで表現
この方法だとUnion Typeを書かず、配列のみの記述でよくなります。
以下がその方法です。
const fruits = ['apple', 'orange', 'grape'] as const;
type fruitType = typeof fruits[number];
おわりに
配列のconstアサーションでUnion Typeを表現することを紹介しました。
この方法のおかげで、Union Typeの種類が増えるたびに配列を編集するようなことはなくなり、配列のみの編集で済むようになります。