You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Object.assign()调用出现重载不匹配错误,如何解决?

修复TypeScript中Object.assign的泛型类型错误

问题代码

export class Attributes<T> {
    constructor(private data: T) {}

    get<K extends keyof T>(key: K): T[K] {
        return this.data[key];
    }

    set(update: T): void {
        Object.assign(this.data, update);
    }
}

错误信息

No overload matches this call.
Overload 1 of 4, '(target: {}, source: T): {} & T', gave the following error.
Argument of type 'T' is not assignable to parameter of type '{}'.
Overload 2 of 4, '(target: object, ...sources: any[]): any', gave the following error.
Argument of type 'T' is not assignable to parameter of type 'object'.ts(2769)
Attributes.ts(1, 25): This type parameter might need an extends {} constraint.
Attributes.ts(1, 25): This type parameter might need an extends object constraint.

修复方案

给泛型T添加extends object约束,确保T只能是对象类型(包括普通对象、数组等),修改后的代码如下:

export class Attributes<T extends object> {
    constructor(private data: T) {}

    get<K extends keyof T>(key: K): T[K] {
        return this.data[key];
    }

    set(update: T): void {
        Object.assign(this.data, update);
    }
}

原因说明

Object.assign的第一个参数要求是对象类型,而原始代码中泛型T没有约束,允许传入number、string这类基本类型,此时调用Object.assign会触发类型不匹配错误。添加extends object约束后,限制了T的范围,确保this.data和update都是对象类型,符合Object.assign的参数要求,错误即可解决。

内容的提问来源于stack exchange,提问作者13reath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 04:21:09