如何解决 TS 报错:T[Extract<keyof T, string>] is not assignable to type (T & U)[Extract<keyof T, string>] ?

代码如下

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 作为函数返回结果的类型?

阅读 2.1k
1 个回答

断言一下。比如

function extend<T extends object, U extends object>(first: T, second: U): T & U {
  const result = {} as T & U
  for (const id in first) {
    ;(<T>result)[id] = first[id]
  }
  for (const id in second) {
    if (!Object.prototype.hasOwnProperty.call(result, id)) {
      ;(<U>result)[id] = second[id]
    }
  }

  return result
}

const x = extend({ a: 'hello' }, { b: 100 });
console.log(x.a, x.b)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题