Typeguard 在等待新的 Promise 中不起作用

Typeguard doesn't work inside await new Promise

我有一个检查 authResponse 是否存在的类型保护。它运行良好,但在 await new Promise 内部我有一个编译器错误,该对象可能为 null。我检查了深层链接条件的类型并且有 AuthResponse,但在新的 Promise 类型中是 AuthResponse |无效的。请你告诉我,是否可以在没有可选链接的情况下使这种类型在新的 Promise 中正常工作?

const hasAuthResponse = (
  response: AuthResponse | null,
): response is AuthResponse => !!response;

if (hasAuthResponse(authResponse)) {
  const deepLink = getRedirectDeepLink(
    redirect_to_scheme,
    "",
    allowedSchemas ?? undefined,
  );

  if (deepLink) {
    router.push({
      pathname: deepLink,
      query: {
        rsid: authResponse.rsid,
      },
    });

    return;
  }

  await new Promise<void>((resolve) => {
    helper
      ? helper.propagateSession(
          authResponse.rsid,
          {
            back: back ?? Urls.PROFILE,
          },
          resolve,
        )
      : resolve();
  });
}

你的例子不是很完整,但我敢打赌 authResponse 可能不是 const

由于 promise 调用是异步的,TypeScript 推断 authResponse 的值在 propagateSession 被调用时可能已经变为 null

简单的解决方法是将 authResponse 重新绑定到本地名称并使用它(因为它保证其类型将保持 AuthResponse):

if (hasAuthResponse(authResponse)) {
    const authResponse2 = authResponse;  // inferred type: AuthResponse

但是因为您实际上只使用 AuthResponse 中的 rsid 字段,所以您可以将它从 authResponse 中解构出来并在后续调用中使用它:

if (hasAuthResponse(authResponse)) {
    const {rsid} = authResponse;