Typed Assertion Functions
- #TypeScript
Typed Assertion Functions
Learn how to tell TypeScript that a function has checked the provided value.
loggedIn?: string;
doSomething() {
this.assertUserIsLoggedIn();
doSomething();
}
assertUserIsLoggedIn() {
if (!this.loggedIn) throw new Error(`User is not logged in`);
}
You will notice TypeScript throws an error because it does not know if the checked value is undefined. Notify TypeScript that the function checked the value by replacing the above function with the following:
assertUserIsLoggedIn(): asserts this is this & { loggedIn: string } {
if (!this.loggedIn) throw new Error(`User is not logged in`);
}
0 Comments
Sign in to join the conversation.