[Typescript] asserts tips
class SDK {
constructor(public loggedInUserId?: string) {}
createPost(title: string) {
this.assertUserIsLoggedIn();
createPost(this.loggedInUserId, title);
}
assertUserIsLoggedIn(): asserts this is this & { loggedInUserId: string } {
if (!this.loggedInUserId) {
throw new Error("User is not logged in");
}
}
}
Basiclly it is a combination assertion
asserts this is this & { loggedInUserId: string }
Assert this is this, return true
and force loggedInUserId to be string type.
Another way
class SDK {
constructor(public loggedInUserId?: string) {}
createPost(title: string) {
this.assertUserIsLoggedIn(this.loggedInUserId);
createPost(this.loggedInUserId, title);
}
assertUserIsLoggedIn(user: string | undefined): asserts user is string {
if (!user) {
throw new Error("User is not logged in");
}
}
}
I prefer this way better