Back to questions
JuniorTheoryCommon
What does tsc say, and what happens when the program runs?
type Cat = { meow: string };
type Dog = { bark: string };
function isCat(pet: Cat | Dog): pet is Cat {
return "bark" in pet;
}
function speak(pet: Cat | Dog) {
if (isCat(pet)) {
console.log(pet.meow.toUpperCase());
}
}
speak({ bark: "woof" });tsc is silent; running it throws a TypeError
- Expecting tsc to catch the wrong body of
isCat: tsc trusts a type predicate and never checks it against the function's code. - Expecting
undefinedto be printed:pet.meowisundefined, and calling a method on it throws aTypeErrorbefore anything is printed.
- How would you fix
isCatso that it keeps its promise? - When does TypeScript infer a type predicate without
pet is Catbeing written?