Created
August 28, 2019 12:14
-
-
Save catwell/bda607d7c31a517d1683bb61c1692383 to your computer and use it in GitHub Desktop.
TypeScript - Type Guard for Discriminated Unions with Extract
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 Chunky { | |
kind: 'chunky'; | |
/* ... */ | |
} | |
export interface Bacon { | |
kind: 'bacon'; | |
/* ... */ | |
} | |
export type Stuff = Chunky | Bacon; | |
type StuffKind = Stuff['kind']; | |
export function stuffIs<T extends StuffKind>(kind: StuffKind, stuff: Stuff): stuff is Extract<Stuff, {kind: T}> { | |
return stuff.kind === kind; | |
} | |
const chunky : Chunky = {kind: 'chunky'}; | |
const bacon : Bacon = {kind: 'bacon'}; | |
console.log( | |
stuffIs('chunky', chunky), /* true */ | |
stuffIs('chunky', bacon), /* false */ | |
stuffIs('bacon', chunky), /* false */ | |
stuffIs('bacon', bacon), /* true */ | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This can be further refined into a point free style like: