Skip to content

Instantly share code, notes, and snippets.

@jasonleehodges
Last active February 13, 2022 23:01
Show Gist options
  • Save jasonleehodges/26897007b0b76ffa77a83ea29112fe68 to your computer and use it in GitHub Desktop.
Save jasonleehodges/26897007b0b76ffa77a83ea29112fe68 to your computer and use it in GitHub Desktop.
Example of when to use Type Guards
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;
};
// 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