typescript - 使用可区分联合类型时出现 TypeScript 错误
问题描述
我正在尝试在 TypeScript 中使用可区分联合类型,但出现以下错误:
Type '{ data: Aaaa | Bbbb; type: "aaaa" | "bbbb"; }' is not assignable to type 'EventData'.
Type '{ data: Aaaa | Bbbb; type: "aaaa" | "bbbb"; }' is not assignable to type '{ type: "bbbb"; data: Bbbb; }'.
Types of property 'type' are incompatible.
Type '"aaaa" | "bbbb"' is not assignable to type '"bbbb"'.
Type '"aaaa"' is not assignable to type '"bbbb"'.
使用以下代码:
export type Aaaa = {
aPropForA: string
}
export type Bbbb = {
somePropsB: number
}
export type EventData =
| { type: 'aaaa'; data: Aaaa }
| { type: 'bbbb'; data: Bbbb }
// simulate getting the data for brevity
declare const data: EventData['data'];
declare const type: EventData['type'];
export const getEventData = (): EventData => {
return { // why is there an error?
data,
type,
}
}
问题的根源是什么?如何在不进行类型转换的情况下修复它?
解决方案
这是一个错误的原因是没有任何东西可以保证 和 的组合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")
}
推荐阅读
- c# - 在 Unity 中为一组 3D 点查找定向边界框
- laravel - 如何在 Laravel Vapor 应用程序中获取 HTTP 请求的 IP?
- python - Python 集中式字典访问
- wordpress - 如何通过右侧栏中的 Wordpress 帖子中的标签显示相关帖子?
- c++ - 为什么我的快速排序无法正常工作?
- python - 为 OptionMenu 选项赋值 Python Tkinter
- ios - 比较 Swift 中的 AVAudioSession.Location 和 AVAudioSession.Orientation
- perl - 如何在 Perl 模块中使用 GetOptions
- velo - 如何在 wix 会员网站上禁用“使用 Google/Facebook 登录”
- php - Laravel 6 - [路由:供应商.destroy] [URI:供应商/{supplier}]缺少必需的参数