Skip to content

Instantly share code, notes, and snippets.



Created Aug 9, 2019
What would you like to do?
A negate function for type guards
type TypeGuard<T, U extends T> = (value: T) => value is U;
const negate = <T, U extends T>(
typeGuard: TypeGuard<T, U>,
): TypeGuard<T, Exclude<T, U>> => (value): value is Exclude<T, U> =>
typeGuard(value) === false;
// Example
const checkIsArray = <T>(value: T | any[]): value is any[] =>
const checkIsNotArray = negate(checkIsArray);
declare const value: string | string[];
if (checkIsNotArray(value)) {
value; // type here is `string` 🎉

This comment has been minimized.

Copy link

@karol-majewski karol-majewski commented Feb 4, 2020

Note: negate can only work if the input type guard is generic. It won't work in situations like this:

declare function isString(candidate: unknown): candidate is string;

const isNotString = negate(isString); // 🤷‍♂️

This comment has been minimized.

Copy link
Owner Author

@OliverJAsh OliverJAsh commented Feb 4, 2020

I think the issue there is that types cannot be excluded from unknown (in this case, Exclude<unknown, string> => unknown).

If you don't use unknown, it works:

declare function isString(candidate: string | number): candidate is string;

… but I guess that's not always an option! I guess Exclude only works for filtering union types, so the parameter has to be a union.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.