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 type guards for TextInput and use them in normalizeText
  2. Create type guards for each User variant
  3. Use the type guards to implement describeUser

Please set the playground first

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