TypeScriptのunion型に感動したので、簡単にメモ。
union型
union型とは、enumのように、型に入る値を定義できるもので、下記の例で、arg
に設定することができるのはa
・b
・c
のいずれかの値になります。
function hoge(arg: 'a' | 'b' | 'c') { console.log(arg) } hoge('a')
例外となる値が入った場合は、下記のようにはじいてくれます。
function hoge(arg: 'a' | 'b' | 'c') { console.log(arg) } hoge('g') // Argument of type '"g"' is not assignable to parameter of type '"a" | "b" | "c"'
union vs enum
「enumじゃなくてunion使えや!」的な記事をよく見かけたので、その理由を調べてみました。
1.数値enumはtype safeではない
enum Hoge { A = 0, B = 1 } const hoge: Hoge = 3 console.log(hoge) // error
2.文字列のenumの冗長性
enum Hoge { A = 'A', B = 'B', C = 'C' }
- const enum を使う場合では、Babelでトランスパイルできないなどの問題もある
またそのほかにも色々理由があるそうです👀(全ては理解してないが、とりあえずunionを使って行こうと思う)
https://www.kabuku.co.jp/developers/good-bye-typescript-enum https://engineering.linecorp.com/ja/blog/typescript-enum-tree-shaking/
てな感じで本日も以上となります🍺