typescript · level 3 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An stops the program when data is wrong.
A type guard answers a question, so you still need an if. Sometimes bad data means there is no point carrying on. An assertion function checks the value and, if it is wrong, uses to stop with an error. If the function returns at all, the value was fine.
Its return type says what it proves: asserts value is number. After the call, the checker treats the value as a number on every line below, with no if needed. Guard when you can recover. Assert when you cannot.
function assertIsNumber(value: unknown, name: string): asserts value is number {
if (typeof value !== "number") {
throw new Error(`${name} must be a number`);
}
}
const reply: unknown = JSON.parse('{"stock": 12}').stock;
assertIsNumber(reply, "stock");
console.log(reply + 1); new Error("...") makes an error with a message, ready to be thrown.
guess first
Shout every input. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function assertIsText(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new Error("Expected text");
}
}
const inputs: unknown[] = ["tea", 7, "cake"];
for (const input of inputs) {
assertIsText(input);
console.log(input.toUpperCase());
}
your turn
Your turn. Welcome a visitor.
Finish the assertion's return type, use the word that stops the program, then type a visitor's name.
fix it
The nickname checks out, but the checker disagrees. Fix it.
- Read the error:
nicknameis stillunknownon line 8, even after the check. - The return type
voidpromises nothing, so the checker learns nothing from the call. - On line 1, change the return type to
asserts value is string.
nailed it
your code refuses bad data at the door. :D
asserts value is Tnarrows the value on every later line.throwstops the program with an error.- Guard when you can recover; assert when you cannot.
new words in your collection
- throw
- assertion function
This lesson isn’t saved. A free account remembers every lesson you finish.