Skip to content

Instantly share code, notes, and snippets.

@michaeljscript
Last active May 19, 2019 19:48
Show Gist options
  • Save michaeljscript/a7177735120d5ab49bb65b81a8f4579a to your computer and use it in GitHub Desktop.
Save michaeljscript/a7177735120d5ab49bb65b81a8f4579a to your computer and use it in GitHub Desktop.
// Parser is a function which takes unknown and returns T or null
type Parser<T> = (val: unknown) => T | null;
// createTypeGuard is a function which takes a parser and returns a new function
// The returned function is a safe type guard for T
const createTypeGuard = <T>(parse: Parser<T>) => (value: unknown): value is T => {
// By assuming that parser returns only T or null
// We can say that value from parser is T when it is not a null
return parse(value) !== null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment