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 an
isStringArraytype guard and use it insidenormalizeText - Create
isAdminUser,isRegularUser, andisGuestUsertype guards and use them indescribeUser - Export
isStringArray,normalizeText,isAdminUser,isRegularUser,isGuestUser, anddescribeUserby name
Completion criteria
- Named exports listed above
isStringArrayis true for string arrays and false for strings / number arrays- User guards are true only for their own shape
normalizeText/describeUserkeep the same exact outputs as the Narrowing step (for exampleAdmin with 2 permissions,Regular user (free),Guest user)