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

Inversify抽象类装饰器搭配protected构造函数报错问题

问题:抽象类构造函数设为protected时的TypeScript错误与Inversify兼容问题

出现的TypeScript错误

Decorator function return type 'abstract new (...args: never) => unknown' is not assignable to type 'void | typeof BaseController'.
  Types of construct signatures are incompatible.
    Type 'abstract new (...args: never) => unknown' is not assignable to type 'abstract new (logger: ILogger) => BaseController'.
      Type 'unknown' is not assignable to type 'BaseController'.ts(1270)
Argument of type 'typeof BaseController' is not assignable to parameter of type 'abstract new (...args: never) => unknown'.
  Cannot assign a 'protected' constructor type to a 'public' constructor type.ts(2345)

代码示例

@injectable()
export abstract class BaseController {
    private readonly _router: Router

    protected constructor(@inject(TYPES.ILogger) private logger: ILogger) {
        this._router = Router();
    }
    //some code
}

原因说明

Inversify的@injectable()装饰器需要访问类的构造函数来完成依赖注入逻辑——哪怕是抽象类,装饰器也需要解析其构造函数的参数类型,为子类的注入继承做准备。

protected修饰的构造函数仅允许在类内部或其子类中调用,而Inversify作为外部库,无法访问protected级别的构造函数。TypeScript的类型检查会识别到这种权限不匹配:装饰器期望接收一个public构造函数类型的类,但你传入的是带protected构造函数的类,因此抛出类型兼容错误。

简单来说,为了让Inversify能正确处理类的依赖注入逻辑,必须将抽象类的构造函数设置为public。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:01:24