Created
July 13, 2022 14:30
-
-
Save rayrayzayzay/56e50a793e3f375ea51ed169b297a90d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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