TypeORM 0.3.x与TypeScript 5装饰器能否共存?配置冲突求解
两种装饰器风格可以共存,但需要适配写法
TypeORM依赖的是旧版实验性装饰器(需要experimentalDecorators和emitDecoratorMetadata配置),而你写的是TypeScript 5.x支持的新版标准装饰器,二者类型检查规则不同,这是报错的根源。
报错原因
旧版方法装饰器的类型要求:装饰器函数的返回值只能是void或TypedPropertyDescriptor<T>;而新版标准装饰器允许直接返回一个新的函数替代原方法,这种返回值不符合旧版类型规则,因此触发ts(1270)错误。
解决方法
要同时兼容TypeORM和自己的装饰器,只需将你的新版装饰器写法适配旧版的类型规范:
调整装饰器写法
将直接返回函数的逻辑,改成修改并返回TypedPropertyDescriptor对象:
// 适配旧版装饰器类型的写法 function myMethodDecorator() { return function( target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<(a: number, b: number) => number> ) { // 保存原方法 const originalMethod = descriptor.value!; // 重写方法逻辑 descriptor.value = function(this: any, a: number, b: number) { console.log("装饰器执行"); return originalMethod.call(this, a, b); }; // 返回修改后的descriptor return descriptor; }; }
保持必要配置
tsconfig.json中必须保留以下配置以满足TypeORM需求:
{ "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true } }
补充说明
目前新版标准装饰器尚未支持自动发射元数据(emitDecoratorMetadata仅对旧版装饰器生效),因此TypeORM暂时无法迁移到新版装饰器。只要将自己的装饰器适配旧版类型规则,就能和TypeORM的装饰器正常共存。
内容的提问来源于stack exchange,提问作者Josh Diehl
相关产品推荐
相关产品推荐

