0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Union型のうれしいところ

0
Posted at

値に複数のパターンがあり得ることを型を以て定義できる。
静的型付け言語において、型で値の取りうる値を定義することは非常に大事。

例えば、aに値が入っている場合はb,cは値なしであるべきだが、
aに値がない場合b,cに値が入っていなければいけないという場合。


type Hoge = {
  a:string
} | {
  b:string,
  c:string
}

という風に書ける。
単なる静的型付け言語やnull安全なだけの言語だと、これらのパターンが存在するということは、
コメントやドキュメントで後続の開発者に伝達する必要があるし、
bに値が存在する時は「当然aは値なしでcは値がある」という前提でのエディタによるコード補完やコンパイル時チェックも入らない。(実際に使うには判別共用体用のタグを足す必要があるが)

値が複数のパターンを取る状態管理などでは非常に有効。

まとめ

  • Union型で複数のパターンを取りうることを型で示すことが出来る
  • 状態管理などで特に有効
  • もっと流行って搭載される言語が増えて欲しい
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?