I am using typescript
2.0.0 with --strictNullChecks
and the following type guard:
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 an inverse of this:
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 accomplish this?
A type guard is a TypeScript technique used to get information about the type of a variable, usually within a conditional block. Type guards are regular functions that return a boolean, taking a type and telling TypeScript if it can be narrowed down to something more specific.
What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .
The ReturnType in TypeScript is a utility type which is quite similar to the Parameters Type. It let's you take the return output of a function, and construct a type based off it.
TypeScript follows possible paths of execution that our programs can take to analyze the most specific possible type of a value at a given position. It looks at these special checks (called type guards) and assignments, and the process of refining types to more specific types than declared is called narrowing.
I stumbled upon the answer; generics. Just narrow in a reverse manner as such:
function isOk<T>(value: T | null | undefined): value is T {
return !isNotOk(value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With