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"?
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.
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)
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