typescript · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A picks one from a menu of values.
A long chain of else if checking one value gets hard to read. A switch looks at one value and jumps to the matching case. Each case names a value, then the lines to run, then break to leave the switch.
The part runs when no case matches, like the else at the end of a chain. Switches suit literal types well, because the checker knows every value on the menu.
When a case ends in return, the function stops there, so no break is needed. Short cases can sit on one line.
type Weather = "sun" | "rain" | "snow";
function pack(weather: Weather): string {
switch (weather) {
case "sun": return "sun cream";
case "rain": return "an umbrella";
default: return "a warm hat";
}
}
console.log(pack("rain"));
console.log(pack("snow")); Write each case value exactly as it appears in the literal type.
guess first
One break is missing. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const time: string = "morning";
switch (time) {
case "morning":
console.log("Good morning!");
case "evening":
console.log("Good evening!");
break;
default:
console.log("Hello!");
}
your turn
Your turn. Price a cinema ticket.
Fill in a price for each kind of ticket, then pick a ticket to buy. Each case returns, so no break is needed.
fix it
Rainy days get no umbrella. Fix it!
- Read the error:
TS2678: Type '"rian"' is not comparable to type 'Weather'.Comparable means it could ever match. - A
Weathercan only be one of the three values on line 1. Compare them with the case on line 5. - Change
"rian"to"rain"on line 5, then press run.
nailed it
you can switch between cases. :D
- A switch jumps to the case that matches its value.
- End each case with
breakorreturn, or it falls through. defaultruns when no case matches.
new words in your collection
- switch
- case
- default
This lesson isn’t saved. A free account remembers every lesson you finish.