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 1 year has passed since last update.

TypeScriptのリテラル型・タプル型・ユニオン型の整理

0
Posted at

りあクト!で学んだ内容を自分の学習メモ的にまとめます。
内容に間違いがあったり、正確じゃない表現の場合はご指摘いただけると幸いです。

リテラル型:型の定義を一意性のあるものにする(type Kで文字列の'kumazaki'を定義したら、Kの型を適用するオブジェクトはkumazakiと完全一致する必要があるし、再代入もできない)

タプル型:型の定義で複数の型を組み合わせるもの。type Aについて[string,number]と定義したら、Aの型を適用するオブジェクトは「文字列、数値」の順と組み合わせで定義されなくてはならない。

ユニオン型:複数の型のうちどれかを適用するもの。type Bについて string | number と定義したら、Bの型を適用するオブジェクトは文字列か数値のどちらかにする必要がある。

これらを組み合わせることもできる。
リテラル型のユニオン型であれば、一意性のある複数の値のうち、どれかにあてはまればいいものになる。

TypeScriptの構文的には
オブジェクトの定義時にas constを加えればオブジェクトの定義と同時にリテラル型のユニオン型として定義できる。
const A = ['abc', 'def', 'ghi']as const;
とすることで、Aは一意性のある'abc''drf''ghi'のいずれかにあてはまればいいものとなる。

一言でまとめると、
「オブジェクトの値を一意性のある再代入不可なものにしたいときは as const を加える」

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?