zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] asserts tips

typescript Tips
2023-09-14 08:59:12 时间
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