Skip to content

Instantly share code, notes, and snippets.

@catwell
Last active August 28, 2019 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save catwell/7f92f7d9a1dc9ab05793bc4da668e2aa to your computer and use it in GitHub Desktop.
Save catwell/7f92f7d9a1dc9ab05793bc4da668e2aa to your computer and use it in GitHub Desktop.
TypeScript Generic Type Guards
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),
);
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