Last active
February 13, 2022 23:01
-
-
Save jasonleehodges/26897007b0b76ffa77a83ea29112fe68 to your computer and use it in GitHub Desktop.
Example of when to use Type Guards
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
export interface Noun { | |
id: string; | |
created?: number; | |
name: string; | |
} | |
export interface Character extends Noun { | |
gender: Gender; | |
} | |
export interface Setting extends Noun { | |
location: string; | |
} | |
// This is the Type Guard to help us correct the errors | |
export const isCharacter = (noun: Noun): noun is Character => { | |
return 'gender' in noun; | |
}; |
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
// Example 1 - extended type | |
function getGender(noun: Noun) { | |
return noun.gender; | |
// Property 'gender' does not exist on type 'Noun'.ts(2339) | |
} | |
// Example 2 - union type | |
function getGender(noun: Character | Setting) { | |
return noun.gender; | |
// Property 'gender' does not exist on type 'Character | Setting'. | |
// Property 'gender' does not exist on type 'Setting'.ts(2339) | |
} | |
// How to correct with a type guard | |
function getGender(noun: Noun) { | |
if (isCharacter(noun)) return noun.gender; | |
throw 'This noun is not a character'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment