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?

ユニオン型の使い方(Typescript)

Posted at

Typescriptの学習を進める中でユニオン型って面白いなと思ったので学習した内容についてまとめてみようと思います

ユニオン型について

まず、ユニオン型ってなんぞやってところからですが、異なる型を"|"を使って区切ることで複数の型を適用できるんです!

具体例としては下記のような感じです。

let id: number | string;  //number型とString型のユニオン型

id = 10; //number型は代入可
id = '10'; //string型は代入可
id = true; //boolean型は代入不可

ちなみにユニオン型を形成する型のことを「メンバー」と呼ぶそうです。

ユニオン型の柔軟性

また、ユニオン型はリテラル型と組み合わせることでより独自性のある柔軟な型を定義することが出来ます。

ちなみにリテラル型というのは、変数の値を特定の文字列や数値に限定できるといった型仕様になります。

具体例としては下記のような感じです。

let dayOfTheWeek: '日' | '月' | '火' | '水' | '木' | '金' | '土';

dayOfTheWeek = '月'; //メンバーに含まれる文字列なので代入可能
dayOfTheWeek = '31'; //代入不可

上記のように、ユニオン型とリテラル型を組み合わせることで代入可能な値を特定の文字列や数値に限定することが出来るということですね!

以上です!

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?