我正在尝试合并可能的对象,并将一个对象转换为另一个对象。
但是typescript和flow都无法识别布尔值是真还是假,而不是别的,如果需要真字面值或假字面值,则可以将布尔值分配给对象洋葱
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
}
}这到底是不是bug?
发布于 2018-10-08 22:50:05
问题是对象字面量既不兼容Bb,也不兼容Cc,因为isFailed是boolean (因为该字段对所有联盟成员都是通用的,所以它将变为true|false,即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
}https://stackoverflow.com/questions/52704679
复制相似问题