WeCodeAcademy

Union and Literal Types

A union A | B allows either type. A literal type allows one exact value. Together they model choices precisely.

Exampletypescript
Open in editor »

Only the listed values are allowed, so typos are caught immediately.

Exampletypescript
Open in editor »
Quick check

What does `type Size = "S" | "M" | "L"` allow?

Your turn: write the code

Define type Switch = "on" | "off" and a function flip(s: Switch): Switch that returns the opposite value. Print flip("on").

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.