typescript · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
is how you prove which type you have.
A string | number value might be either, so the checker only lets you do things that work on both. Call .toUpperCase() on it and you get TS2339, because numbers have no such method.
So ask first. Inside if (typeof code === "string"), the checker knows code is a string, and string methods work. In the else, only number is left. This is narrowing: each check makes the list of possible types shorter.
Checking !== null narrows too. After if (answer !== null), a string | null is a plain string.
function label(code: string | number): string {
if (typeof code === "string") {
return code.toUpperCase();
} else {
return `No. ${code}`;
}
}
console.log(label("b12"));
console.log(label(7)); Narrowing only lasts inside the block where the check was made.
guess first
Narrowed before use. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function tidy(answer: string | null): string {
if (answer !== null) {
return answer.trim().toLowerCase();
}
return "no answer";
}
console.log(tidy(" YES "));
console.log(tidy(null));
your turn
Your turn. Weigh a parcel either way.
A parcel's weight comes as a number of grams, or as text like "2kg". Fill in the type for the typeof check, so each kind gets the right message.
fix it
You cannot shout at nobody. Fix it!
- Read the error:
TS18047: 'name' is possibly 'null'.What should happen when there is no name? - Before line 2, check whether name is
nulland return a message if it is. After that check, name must be a string. - Add
if (name === null) { return "Nobody to shout at!"; }before line 2, then press run.
nailed it
you can prove which type you have. :D
- Narrowing uses checks like
typeofto shrink a union. - Inside the check, the checker knows the exact type.
- Check for
nullbefore using a value that might be missing.
new words in your collection
- narrowing
This lesson isn’t saved. A free account remembers every lesson you finish.