Skip to content

Instantly share code, notes, and snippets.

@rayrayzayzay
Created July 13, 2022 14:30
Show Gist options
  • Save rayrayzayzay/56e50a793e3f375ea51ed169b297a90d to your computer and use it in GitHub Desktop.
Save rayrayzayzay/56e50a793e3f375ea51ed169b297a90d to your computer and use it in GitHub Desktop.
type Dog = {
numberOfLegs: number
collar: {
name: string
material: "leather" | "plastic"
}
}
type Cat = {
numberOfLegs: number
microchip: {
id: string
name: string
}
}
type Pet = Dog | Cat
function numberOfLegs(pet: Pet): number {
return pet.numberOfLegs //
this is fine as all pets share a common property
}
function getName(pet: Pet): string {
// If it's a dog, read the collar
// If it's a cat, read the microchip
// ^-- Figuring this out is type narrowing
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment