首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用两个可能的值输入提示承诺响应

用两个可能的值输入提示承诺响应
EN

Stack Overflow用户
提问于 2020-05-04 17:59:27
回答 1查看 29关注 0票数 0

我有以下TypeScript函数定义:

代码语言:javascript
运行
复制
export const handler = async (): Promise<LambdaOutput | DCDErrorResponse> => {
 const result1: Promise<LambdaOutput> = await func1();
 const result2: Promise<DCDErrorResponse> = await func2();

 return someMagicalCondition() ? result1 : result2;
};

另一段代码导入handler()并执行它:

代码语言:javascript
运行
复制
const result = await handler();
console.log(result.upload); // <-- fail to access attributes, available in the LambdaOutput type but not in the other possible return type of the Promise

问题是,每当我在最后一个示例中尝试访问result.upload (一个属性,该属性仅在LambdaOutput中可用,而不是在DCDErrorResponse中可用)时,TypeScript编译器就会抱怨:

TS2339:属性'upload‘不存在于'LambdaOutput \\ DCDErrorResponse’类型上。“DCDErrorResponse”类型上不存在其他属性“upload”。

EN

回答 1

Stack Overflow用户

发布于 2020-05-04 18:16:59

由于您的返回值可能是多个数据类型,因此在开始将其视为其中一种数据类型之前,您必须检查以确保它是您真正想要的类型。在这种情况下,您应该能够检查该属性是否存在。然后,类型记录可以锁定在代码分支中的正确类型。

代码语言:javascript
运行
复制
const result = await handler();
if ('upload' in result) {
   // Typescript knows result is a LambdaOutput here
   console.log(result.upload);
}

游乐场

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61598662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档