typescript · level 2 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A allows only the exact values you list.
A string box takes any text at all, typos included. Often only a few values make sense. A coffee comes in small, medium or large, and nothing else.
A literal type is one exact value used as a type, like "small". Join several with | and you get a short menu: type Size = "small" | "medium" | "large";. Anything else, like "huge" or "meduim", is a TS2322 before your code runs.
A const box keeps its literal type. After const size = "small"; the checker knows it is exactly "small", not any string.
type Size = "small" | "medium" | "large";
type Drink = { name: string; size: Size };
const order: Drink = { name: "latte", size: "medium" };
console.log(`One ${order.size} ${order.name}, please.`);
order.size = "large";
console.log(`Make that ${order.size}!`); Literal types work with numbers too, like type Dice = 1 | 2 | 3 | 4 | 5 | 6;.
guess first
Traffic lights have three colours. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Light = "red" | "amber" | "green";
let light: Light = "red";
light = "amber";
light = "blue";
console.log(light);
your turn
Your turn. Book a seat on the train.
Choose a coach from the three on the menu and any seat number, then run it. Then try a coach that is not on the menu and read the error.
fix it
This T-shirt order will not go through. Fix it!
- Read the error:
TS2322: Type '"m"' is not assignable to type 'Size'. - Literal types are exact, and that includes capitals. Look at how the sizes are written on line 1.
- Change
"m"to"M"on line 3, then press run.
nailed it
your types have exact menus now. :D
- A literal type is one exact value, like
"small". - Join literal types with
|to make a short menu. - Typos in literal values are caught before you run.
new words in your collection
- literal type
This lesson isn’t saved. A free account remembers every lesson you finish.