javascript - 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();
});
}
解决方案
你的例子并不完整,但我敢打赌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;
推荐阅读
- c++ - 特定时间戳的 WinAPI 调用代码
- reactjs - componentDidMount 中的多次调度
- typo3 - maxWInText TypoScript 设置对 Youtube 视频无效
- ios - 说明 NSLayoutConstraint 到框架
- javascript - 是否可以在 javascript 正则表达式中匹配我的捕获组匹配的字符串中的字符串?
- javascript - Javascript 图像预览
- mysql - 如果其中一个值在 Mysql 中有特定变量,如何改进选择范围
- protractor - 量角器中文本字段的值 - 未定义
- html - 如何均匀地间隔下拉框?
- c# - 如何在 c# Windows 窗体中将带十进制的文本框字符串转换为十进制。