Type Guards
Type Guards
π¨βπΌ We keep writing the same checks to narrow our union types. Let's extract
those checks into reusable type guard functions.
In functional programming, these are called predicatesβfunctions that test
something and return true or false.
TypeScript type guards use the special
is return type to tell the compiler
what type a value is when the predicate returns true:type Cat = { meow(): void }
type Dog = { bark(): void }
type Pet = Cat | Dog
function isCat(pet: Pet): pet is Cat {
return 'meow' in pet
}
function speak(pet: Pet) {
if (isCat(pet)) {
pet.meow() // β
TypeScript knows it's a Cat
} else {
pet.bark() // β
TypeScript knows it's a Dog
}
}
π¨ Open
and:
- Create type guards for
TextInputand use them innormalizeText - Create type guards for each
Uservariant - Use the type guards to implement
describeUser