联合类型无法在孤立的上下文中工作
union type not able to work within an isolated context
我有以下代码:
if (event.hasOwnProperty('body')) {
Context.request = JSON.parse(event.body) as T;
} else {
Context.request = event;
}
其中 event
定义为:
private static event: aws.IGatewayEvent | ut.IGenericEvent;
第一个定义有一个 "body" 属性,第二个没有。我仍然希望我的条件语句应该让 Typescript 看到剩下的唯一情况——也就是对象实现 aws.IGatewayEvent
接口的地方——而不是给出错误:
Property 'body' does not exist on type 'IGenericEvent | IGatewayEvent'.
Property 'body' does not exist on type 'IGenericEvent | IGatewayEvent'.
属性 检查不会在 TypeScript 中形成自动类型保护。您现在必须创建一个用户定义的类型保护。
更多
我有以下代码:
if (event.hasOwnProperty('body')) {
Context.request = JSON.parse(event.body) as T;
} else {
Context.request = event;
}
其中 event
定义为:
private static event: aws.IGatewayEvent | ut.IGenericEvent;
第一个定义有一个 "body" 属性,第二个没有。我仍然希望我的条件语句应该让 Typescript 看到剩下的唯一情况——也就是对象实现 aws.IGatewayEvent
接口的地方——而不是给出错误:
Property 'body' does not exist on type 'IGenericEvent | IGatewayEvent'.
Property 'body' does not exist on type 'IGenericEvent | IGatewayEvent'.
属性 检查不会在 TypeScript 中形成自动类型保护。您现在必须创建一个用户定义的类型保护。