typescript · level 3 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A teaches the checker your own test.
Data from outside, such as JSON, should arrive as unknown. You can check it with typeof and in, but that narrowing only lasts inside one if. Move the checks into a function and the narrowing is lost, unless the function says what its answer proves.
A return type like value is Pet is a . The function returns a boolean, and when the answer is true the checker treats the value as a Pet. A function like that is a type guard: write it once and reuse it everywhere.
interface Pet {
name: string;
age: number;
}
function isPet(value: unknown): value is Pet {
if (typeof value !== "object" || value === null) {
return false;
}
return "name" in value && typeof value.name === "string" && "age" in value && typeof value.age === "number";
}
const data: unknown = JSON.parse('{"name": "Rex", "age": 4}');
if (isPet(data)) {
console.log(`${data.name} is ${data.age}`);
} The checker trusts a type predicate completely, so make sure the checks inside are honest.
guess first
A guard that always says yes. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function isText(value: unknown): value is string {
return true;
}
const input: unknown = 42;
if (isText(input)) {
console.log(input.toUpperCase());
}
your turn
Your turn. Guard the playlist.
Finish the type predicate so isSong narrows its value to a Song, then give the first track a title.
fix it
The parcel guard trips over nothing. Fix it.
- Read the error: the checker says
valueis possiblynull. How can an object benull? typeof nullis"object"too, a famous JavaScript quirk. The guard must rulenullout.- On line 3, add
value !== null &&straight after thetypeofcheck.
nailed it
your own checks now count for the checker. :D
- A type predicate like
value is Petgoes in the return type. - Check
unknowndata once in a guard, then reuse it everywhere. - The checker trusts guards completely, so keep them honest.
new words in your collection
- type predicate
- type guard
This lesson isn’t saved. A free account remembers every lesson you finish.