Issue
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"?
Solution
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
)
Answered By - Titian Cernicova-Dragomir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.