Created
January 20, 2021 11:16
-
-
Save safareli/6356ba19296336f8916823ba738a19b1 to your computer and use it in GitHub Desktop.
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
/** | |
* Stricter and Safer version of Type Guards. | |
* | |
* It takes function that actually returns Output type and constructs | |
* type guard which is actually safe and can't ever go out of sync. | |
* for example this type guard compiles: | |
* ```ts | |
* function isNumber(x: any): x is number { | |
* return typeof x === "string"; | |
* } | |
* ``` | |
* | |
* While using `is` you can't write such gibberish. | |
* ```ts | |
* is(function isNumber(x: unknown) { | |
* return typeof x === "number" ? x : undefined; | |
* }) // : (value: unknown) => value is number | |
* ``` | |
*/ | |
export function is<Input, Output extends Input, Args extends unknown[]>( | |
f: (value: Input, ...args: Args) => Output | undefined | |
) { | |
return (value: Input, ...args: Args): value is Output => { | |
if (f(value, ...args) !== undefined) { | |
return true; | |
} | |
{ | |
return false; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment