javascript - 与不相交的工会感到困惑
问题描述
我正在尝试合并可能的对象并将一个对象转换为另一个对象
但是打字稿和流程都无法识别布尔值是真还是假,没有别的,可以将布尔值分配给需要以太真文字或假文字的对象洋葱
type Aa = {
isFetching: false,
isFailed: false,
isFetched: false
}
type Bb = {
isFetching: true,
isFailed: false,
isFetched: false
}
type Cc = {
isFetching: true,
isFailed: true,
isFetched: false
}
type Dd = {
isFetching: false,
isFailed: true,
isFetched: false
}
type Data = Aa | Bb | Cc | Dd
function thisWorks(data: Data): Data {
if (data.isFailed) {
return {
isFetching: true,
isFailed: true,
isFetched: data.isFetched
}
} else {
return {
isFetching: true,
isFailed: false,
isFetched: data.isFetched
}
}
}
function thisDoesNot(data: Data): Data {
return {
isFetching: true,
isFailed: data.isFailed,
isFetched: data.isFetched
}
}
这是不是这个错误?
解决方案
问题是对象文字既不兼容Bb
or Cc
,因为isFailed
is boolean
(因为该字段对联合的所有成员都是通用的,它将变成true|false
which is booelan
)
最简单的解决方案是对联合使用类型断言。这将保留一些检查,但允许分配发生:
function thisDoesNot(data: Data): Data {
return {
isFetching: true,
isFailed: data.isFailed,
isFetched: data.isFetched
} as Data
}
这将是一个错误:
function thisDoesNot(data: Data): Data {
return {
isFetching: 1,
isFailed: data.isFailed,
isFetched: data.isFetched
} as Data
}
但是,我们确实会丢失多余的财产检查,这将是有效的:
function thisDoesNot(data: Data): Data {
return {
excess: 1,
isFetching: true,
isFailed: data.isFailed,
isFetched: data.isFetched
} as Data
}
推荐阅读
- html - 如何并排对齐两个元素并将它们居中
- android - Android kotlin 调试协程
- javascript - 为什么绿色文本在空格后转到下一行?
- javascript - 反应三纤维等效于 scene.add() - 使用反应三纤维的 2D 文本精灵
- javascript - JS 函数不能从 KeyCode 工作/我如何用键盘键调用这个 JS 函数
- php - PHP 邮件脚本在 IONOS Server 上不起作用
- python - 使用 Nan vaules 创建一个新的 Excel 电子表格
- c - getcwd() vs get_current_dir_name()?
- angular - 无法使用 Angular Animations 正确设置 Carousel
- javascript - 处理 ' 在 JS