这是一个错误的原因是没有什么能保证
data
和
type
是正确的。在本代码中,赋值是有效的,并且会导致不正确的联合:
const data: EventData['data'] = { aPropForA: ""};
const type: EventData['type'] = "bbbb"
export const getEventData = (): EventData => {
return { // why is there an error?
data,
type,
}
}
在没有类型断言的情况下绕过错误的唯一方法是进行所需的检查:
declare const data: EventData['data'];
declare const type: EventData['type'];
export const getEventData = (): EventData => {
if(type === 'aaaa' && 'aPropForA' in data) {
return { data, type,}
} else if(type === 'bbbb' && 'somePropsB' in data) {
return { data, type,}
}
throw new Error("Invalid combination")
}