打字稿,类型保护在异步函数中无法正常工作?

Typescript, type guards not working correctly in async functions?

我正在尝试使用 typescript 和 firebase/store 为用户角色实现一个 auth 函数,并且在异步函数中使用类型保护时注意到一些奇怪的事情。特别是 .then().

以下是存在问题的代码片段(为简洁起见,断章取义):

authUser: firebase.User | null;
...

if (authUser) {
  this.user(authUser.uid)
    .get()
    .then(snapshot => {
      const dbUser = snapshot.data();
      if (dbUser && !dbUser.roles) dbUser.roles = {};
      authUser = {
          uid: authUser.uid,
          email: authUser.email,
          emailVerified: authUser.emailVerified,
          providerData: authUser.providerData,
          ...dbUser,
      };
      next(authUser);
    });
} else {
  ...
}

typescript 编译器抱怨在 authUser = { uid: authuser.uid ... } 块中,authUser 可能是 null。当它在 if 语句中时,这怎么可能?这和函数异步有关系吗?

虽然当您触发承诺时 authUser 不为空,但根据时间的不同,当承诺履行时它可能为空。因此,编译器正确地抱怨它可能为空。请记住,稍后会在不确定的时间发生,其他代码可能会在那时更改它。

您随后需要检查和处理案例,以处理可能出现的任何时序情况。