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
index.ts
and:
  1. Create an isStringArray type guard and use it inside normalizeText
  2. Create isAdminUser, isRegularUser, and isGuestUser type guards and use them in describeUser
  3. Export isStringArray, normalizeText, isAdminUser, isRegularUser, isGuestUser, and describeUser by name

Completion criteria

  • Named exports listed above
  • isStringArray is true for string arrays and false for strings / number arrays
  • User guards are true only for their own shape
  • normalizeText / describeUser keep the same exact outputs as the Narrowing step (for example Admin with 2 permissions, Regular user (free), Guest user)

Please set the playground first

Loading "Type Guards"
Loading "Type Guards"
Login to get access to the exclusive discord channel.
Loading Discord Posts