Last active
May 19, 2019 19:48
-
-
Save michaeljscript/a7177735120d5ab49bb65b81a8f4579a to your computer and use it in GitHub Desktop.
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
// 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