Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom TypeScript type guard for "not undefined" in separate function

Tags:

typescript

This won't compile:

public hello(user?: User): void {
  // ...do some stuff
  console.log(user.toString());      // error: "Object is possibly undefined" 
}

That can be fixed with a type guard:

if (!user) throw Error();

But I want to move that into a separate function, so I tried

private guard(arg: unknown): arg is object {
  if (!arg) throw Error();
}

and I tried

private guard(arg: unknown): arg is object {
 return arg !== undefined;
}

But that doesn't work.

How do I write a custom type guard in a separate function, to assert "not undefined"?

like image 455
lonix Avatar asked Feb 17 '19 17:02

lonix


Video Answer


2 Answers

You could use a template function like this:

function isDefined<T>(val: T | undefined | null): val is T {
    return val !== undefined && val !== null;
}

This one checks for not undefined and not null.

like image 180
Krisztián Balla Avatar answered Oct 19 '22 17:10

Krisztián Balla


The code you have should work, this contained example works as is:

type User = { a: string }
function hello(user?: User): void {
  if (guard(user)) {
    console.log(user.toString());
  }
}

function guard(arg: unknown): arg is object {
  return arg !== undefined;
}

If you are looking for a version that does not require an if that is not currently possible, all type guards require some form of conditional statement (if or switch)

like image 1
Titian Cernicova-Dragomir Avatar answered Oct 19 '22 19:10

Titian Cernicova-Dragomir