Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse TypeScript Type Guard

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?

like image 626
Deathspike Avatar asked Jul 27 '16 19:07

Deathspike


People also ask

What is type guard in TypeScript?

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 is ?: In TypeScript?

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 .

What is ReturnType in TypeScript?

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.

What is narrowing in TypeScript?

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.


1 Answers

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);
}
like image 124
Deathspike Avatar answered Oct 21 '22 09:10

Deathspike