我具有以下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”上不存在属性“上载”。
const result = await handler();
if ('upload' in result) {
// Typescript knows result is a LambdaOutput here
console.log(result.upload);
}
Playground