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

tsyringe自动注入报错TypeInfo not known for 'C',求排查原因

tsyrine依赖注入报错:TypeInfo not known for "C" 的原因及解决

问题场景

执行以下代码时抛出错误:

import "reflect-metadata";
import { container, injectable } from "tsyringe";

@injectable()
class B{}

@injectable()
class C{
    constructor(b: B){}
}

container.resolve(C); // Uncaught Error: TypeInfo not known for "C"

但给C的构造函数参数加上@inject(B)装饰器后,代码恢复正常:

import "reflect-metadata";
import { container, injectable, inject } from "tsyringe";

@injectable()
class B{}

@injectable()
class C{
    constructor(@inject(B) b: B){}
}

container.resolve(C); // 正常运行

对比官方无接口示例可正常执行,本地代码却出现差异,原因如下:

核心原因

tsyringe实现隐式依赖注入的前提是TypeScript编译时生成反射元数据,这需要开启两个编译选项:

  • experimentalDecorators:启用装饰器语法
  • emitDecoratorMetadata:让TypeScript为装饰器生成额外的元数据(包括构造函数参数的类型信息)

如果你的tsconfig.json未开启emitDecoratorMetadata,tsyringe无法自动识别C的构造函数参数b的类型是B,因此抛出TypeInfo not known错误。而官方示例的编译配置是正确开启这两个选项的,所以无需手动添加@inject;你的环境没开配置,必须通过@inject(B)显式指定依赖类型才能完成解析。

解决步骤

修改tsconfig.json中的compilerOptions:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

开启后,tsyringe就能通过反射元数据自动推断参数类型,无需手动添加@inject装饰器即可实现隐式注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 06:22:19