老师再视频中演示的时候,并没有解释为什么要这样做。
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'.
//...
希望老师能解答一下