Last active
August 28, 2019 12:02
-
-
Save catwell/7f92f7d9a1dc9ab05793bc4da668e2aa to your computer and use it in GitHub Desktop.
TypeScript Generic Type Guards
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
interface _typeMap { | |
chunky: Chunky; | |
bacon: Bacon; | |
} | |
type _stuffKind = keyof _typeMap; | |
export interface Stuff { | |
kind: _stuffKind; | |
/* ... */ | |
} | |
export interface Chunky extends Stuff { | |
kind: 'chunky'; | |
/* ... */ | |
} | |
export interface Bacon extends Stuff { | |
kind: 'bacon'; | |
/* ... */ | |
} | |
type _mappedType<T extends _stuffKind> = _typeMap[T]; | |
export function stuffIs<T extends _stuffKind>(kind: _stuffKind, stuff: Stuff): stuff is _mappedType<T> { | |
return stuff.kind === kind; | |
} | |
const chunky : Chunky = {kind: 'chunky'}; | |
const bacon : Bacon = {kind: 'bacon'}; | |
console.log( | |
stuffIs('chunky', chunky), | |
stuffIs('chunky', bacon), | |
stuffIs('bacon', chunky), | |
stuffIs('bacon', bacon), | |
); |
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
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), | |
stuffIs('chunky', bacon), | |
stuffIs('bacon', chunky), | |
stuffIs('bacon', bacon), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment