Skip to content

Instantly share code, notes, and snippets.

@safareli
Created January 20, 2021 11:16
Show Gist options
  • Save safareli/6356ba19296336f8916823ba738a19b1 to your computer and use it in GitHub Desktop.
Save safareli/6356ba19296336f8916823ba738a19b1 to your computer and use it in GitHub Desktop.
/**
* 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