类型提示有两个可能值的Promise响应

问题描述 投票:0回答:1

我具有以下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:类型'LambdaOutput |中没有属性'上载' DCDErrorResponse”。类型“ DCDErrorResponse”上不存在属性“上载”。

typescript type-hinting
1个回答
1
投票
由于您的返回值可能是多种数据类型,因此在开始像那些类型之一之前,您必须检查以确保它是您真正想要的类型。在这种情况下,您应该能够检查该属性是否存在。然后Typescript可以锁定该代码分支中的正确类型。

const result = await handler(); if ('upload' in result) { // Typescript knows result is a LambdaOutput here console.log(result.upload); }

Playground
© www.soinside.com 2019 - 2024. All rights reserved.