LoginSignup
3
2

More than 3 years have passed since last update.

[TypeScript 3.4] 配列のconstアサーションでUnion Typeを表現する

Last updated at Posted at 2019-06-18

はじめに

例えば以下のように、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の種類が増えるたびに配列を編集するようなことはなくなり、配列のみの編集で済むようになります。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2