TypeScript5.4+版本中NestJS@InjectModel装饰器的ESLint警告与测试问题
NestJS + TypeScript 5.4: 解决ESLint/TS警告 "Unable to resolve signature of parameter decorator..."
问题原因
- TypeScript 4.9+对参数装饰器的类型检查逻辑进行了强化,要求装饰器参数必须是明确的
string | symbol类型,不允许可能为undefined的值 @nestjs/mongoose旧版本的类型定义未完全适配TS 5.4的严格检查规则,导致当传入的Schema名称(如TripsSchemaName)在静态类型推断中存在undefined可能性时,触发TS1239错误- 尽管运行时
TripsSchemaName是有效字符串,但TS静态检查无法确认其非空性,导致装饰器参数类型不匹配
解决方法
1. 确保Schema名称为明确的非空字符串类型
如果有权限修改@transporter-asia/schema包,将Schema名称定义为常量类型:
// 在@transporter-asia/schema包中 export const TripsSchemaName = 'Trip' as const;
若无法修改依赖包,在使用@InjectModel时添加非空断言:
// trips.repository.ts @InjectModel(TripsSchemaName!) private tripsDocumentModel: Model<TripsDocument>,
2. 更新@nestjs/mongoose到兼容TS 5.4的版本
运行以下命令更新依赖:
npm install @nestjs/mongoose@latest mongoose@latest
新版本的@nestjs/mongoose会适配TS 5.4的装饰器类型规则,从根源解决类型不兼容问题。
3. 调整TS/ESLint配置临时规避(不推荐长期使用)
如果暂时无法更新依赖,可在tsconfig.json中开启跳过库类型检查:
{ "compilerOptions": { "skipLibCheck": true } }
或在.eslintrc.js中禁用相关规则:
module.exports = { rules: { '@typescript-eslint/no-unsafe-argument': 'off' } };
4. 修正测试文件中的类型问题
在测试用例中,确保getModelToken的参数为明确非空值:
// trips.repository.spec.ts { provide: getModelToken(TripsSchemaName!), useValue: tripMockDataModel },
验证
修改后运行以下命令确认警告消失:
npm run lint npx tsc --noEmit
内容的提问来源于stack exchange,提问作者harshad P P
相关产品推荐
相关产品推荐

