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

创建TypeScript空操作类装饰器遇TS2509错误,求解决方案

问题:TypeScript空操作类装饰器编译报错

我尝试创建一个不执行任何操作的基础TypeScript类装饰器,代码如下:

const test = () => <T extends new (...rest: any[]) => InstanceType<T>> (Target: T) => {
    class NewTarget extends Target {}

    Object.setPrototypeOf(NewTarget.prototype, Object.getPrototypeOf(Target.prototype));

    return NewTarget;
};

使用示例:

@test()
class Test {}

new Test();

这段代码无法编译,报错信息:

Base constructor return type 'InstanceType<T>' is not an object type or intersection of object types with statically known members ts(2509)

解决方案

问题出在泛型约束的循环引用上:InstanceType<T>依赖于构造函数T的实例类型,但你在约束T的时候又用了InstanceType<T>,导致TypeScript无法解析出明确的对象类型,触发了ts(2509)错误。

只需要把泛型约束改为直接限定构造函数返回对象类型即可,修正后的代码:

const test = () => <T extends new (...rest: any[]) => object>(Target: T) => {
    class NewTarget extends Target {}

    Object.setPrototypeOf(NewTarget.prototype, Object.getPrototypeOf(Target.prototype));

    return NewTarget;
};

或者更严谨地约束实例类型为非原始类型(类的实例必然是对象),也可以写成:

const test = () => <T extends new (...rest: any[]) => {}>(Target: T) => {
    class NewTarget extends Target {}

    Object.setPrototypeOf(NewTarget.prototype, Object.getPrototypeOf(Target.prototype));

    return NewTarget;
};

修正后代码可以正常编译,原使用示例无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:40:35