首页 > 解决方案 > Typeguard 在 await new Promise 内部不起作用

问题描述

我有一个 typeguard 检查 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();
  });
}

标签: javascripttypescripttypescript-typingstypeguards

解决方案


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

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

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

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

但由于您只真正使用rsid来自 AuthResponse 的字段,因此您可以将其解构authResponse并在后续调用中使用它:

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

推荐阅读