0

我有以下 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 | 类型”上不存在属性“上传” DCD错误响应'。“DCDErrorResponse”类型上不存在属性“上传”。

4

1 回答 1

2

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

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

操场

于 2020-05-04T18:16:59.070 回答