Inverse TypeScript Type Guard

I am using typescript 2.0.0 with --strictNullChecks and the following guard type:

 function isNotOk(value: any): value is null | undefined { if (typeof value === 'number') { return !isFinite(value); } else { return value === null || value === undefined; } } 

Which invalidates null , undefined , NaN and Infinite . I want this to be the opposite:

 export function isOk(value: any): value is not null | undefined { return !isNotOk(value); } 

Of course, this syntax does not work. Is there a known way to do this?

+6
source share
1 answer

I came across an answer; generics. Just tapering in the reverse order:

 function isOk<T>(value: T | null | undefined): value is T { return !isNotOk(value); } 
+9
source

All Articles