我有以下TypeScript函数定义:
export const handler = async (): Promise<LambdaOutput | DCDErrorResponse> => {
const result1: Promise<LambdaOutput> = await func1();
const result2: Promise<DCDErrorResponse> = await func2();
return someMagicalCondition() ? result1 : result2;
};另一段代码导入handler()并执行它:
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”。
发布于 2020-05-04 18:16:59
由于您的返回值可能是多个数据类型,因此在开始将其视为其中一种数据类型之前,您必须检查以确保它是您真正想要的类型。在这种情况下,您应该能够检查该属性是否存在。然后,类型记录可以锁定在代码分支中的正确类型。
const result = await handler();
if ('upload' in result) {
// Typescript knows result is a LambdaOutput here
console.log(result.upload);
}https://stackoverflow.com/questions/61598662
复制相似问题