• 欢迎光临~

[Typescript] Tips: Use assertion functions inside classes

开发技术 开发技术 2022-10-22 次浏览

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");
    }
  }
}

 

程序员灯塔
转载请注明原文链接:[Typescript] Tips: Use assertion functions inside classes
喜欢 (0)
违法和不良信息举报电话:022-22558618 举报邮箱:dljd@tidljd.com