最近,我遇到了一个需要缩小具有联合类型属性的Obj的情况. 以下是我试图实现的简化版本.
interface typeA{
id: number,
status: 0 | 1,
}
interface typeB extends typeA {
status: 1,
}
function log(param: typeB){
// only accepts status = 1
}
但是,当try 对类型A的数据使用function log
时,我会遇到以下错误:
Argument of type 'typeA' is not assignable to parameter of type 'typeB'.
Types of property 'status' are incompatible.
Type '0 | 1' is not assignable to type '1'.
Type '0' is not assignable to type '1'
代码:
const data1: typeA = {id: 1, status: 0}
data1.status = 1
if(data1.status === 1){
data1.status // when hovered, typescript can correctly identify that data1.status is 1
log(data1) // error here
}
我现在像这样克服了错误,但我不确定是否有更好的打字操作符,所以解决我的问题
if(data1.status === 1){
log({...data1, status: data1.status})
}