为什么要加 as any
来源:3-23 高级类型 - 交叉类型

慕莱坞0998854
2020-06-29
老师再视频中演示的时候,并没有解释为什么要这样做。
function extend<T extends object,U extends object>(first:T,second:U):T&U{
let result = {} as T & U
for(let id in first){
// 这里
result[id] = first[id] as any
}
for(let id in second){
if(!result.hasOwnProperty(id)){
// 这里
result[id] = second[id] as any
}
}
return result
}
我觉得这里result 被 断言为 T&U类型,那就说明result包含类型T和U上的所有属性并且类型会保持一致,所以我们没理由要加上as any 啊,但是不加这句又会像视频中演示的那样报错:
Type 'T[Extract<keyof T, string>]' is not assignable to type '(T & U)[Extract<keyof T, string>]'.
Type 'T' is not assignable to type 'T & U'.
Type 'object' is not assignable to type 'T & U'.
Type 'object' is not assignable to type 'T'.
'object' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'object'.
//...
希望老师能解答一下
写回答
1回答
-
ustbhuangyi
2020-06-29
Type 'T' is not assignable to type 'T & U'.
重点看这句,由于是交叉类型,所以赋值给 T & U 的必须要 T 和 U 的类型都满足,而 T 不包含 U 的类型,所以会报错。012020-06-30
相似问题