代码如下
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]; // 这里报错
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
result[id] = second[id]; // 这里报错
}
}
return result;
}
const x = extend({ a: 'hello' }, { b: 100 });
console.log(x.a, x.b)
报错信息如下
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'.
Type 'T' is not assignable to type 'U'.
'T' is assignable to the constraint of type 'U', but 'U' could be instantiated with a different subtype of constraint 'object'.
是不是这种情况不应该用 T&U 作为函数返回结果的类型?
断言一下。比如