You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typeguard在await new Promise内失效,无需可选链的修复方案是什么?

问题原因

TypeScript 无法跨异步回调作用域保留类型收窄结果。编译器无法保证 Promise 回调执行前,外部的 authResponse 没有被重新赋值为 null,因此进入回调后会自动恢复到收窄前的 AuthResponse | null 联合类型。

解决方案(无需可选链)

在类型收窄后的代码块内,将 authResponse 赋值给 const 修饰的局部常量。const 常量赋值后不可修改,TypeScript 可以稳定识别其类型为非空的 AuthResponse。

修改后的代码示例:

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

if (hasAuthResponse(authResponse)) {
  // 赋值给const局部常量,固定类型
  const validAuth = authResponse;
  const deepLink = getRedirectDeepLink(
    redirect_to_scheme,
    "",
    allowedSchemas ?? undefined,
  );

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

    return;
  }

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

可选简化方案

如果你能100%确定回调执行时authResponse一定不为空,也可以直接使用非空断言操作符!,无需额外声明变量:

// 直接在使用处加!告诉编译器该值非空
authResponse!.rsid

内容的提问来源于stack exchange,提问作者Dmitry Mishin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:54:03