[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

 

posted @ 2022-04-25 14:42  Zhentiw  阅读(43)  评论(0编辑  收藏  举报