You can do some really, really neat stuff with assertion functions inside classes.
Here, we assert that the user is logged in and get proper inference on the user's logged in user id.
export 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");
}
}
}
标签:functions,Typescript,string,inside,logged,assertion,loggedInUserId,user From: https://www.cnblogs.com/Answer1215/p/16815198.html