首页 > 其他分享 >[Typescript] Tips: Use assertion functions inside classes

[Typescript] Tips: Use assertion functions inside classes

时间:2022-10-22 02:33:05浏览次数:93  
标签:functions Typescript string inside logged assertion loggedInUserId user

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

相关文章