Created
August 11, 2022 09:49
-
-
Save bennycode/09b3d247d03e0651621ae69804dcb4c1 to your computer and use it in GitHub Desktop.
Type Guard
This file contains hidden or 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 = { | |
age: number; | |
name: string; | |
bark: () => void; | |
type: 'dog' | |
} | |
type Person = { | |
age: number; | |
name: string; | |
shout: () => void; | |
type: 'person' | |
} | |
function makeNoise(dogOrPerson: Dog | Person): void { | |
switch (dogOrPerson.type) { | |
case 'dog': | |
// Type is narrowed to "Dog", so we can "bark": | |
dogOrPerson.bark(); | |
break; | |
case 'person': | |
// Type is narrowed to "Person", so we can "shout": | |
dogOrPerson.shout(); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment