NestJs 类型错误 - “undefined”类型的参数不可分配给“string |”类型的参数符号'

问题描述 投票:0回答:1

在 NestJs 中使用 InjectRepository 装饰器时突然出现类型错误。每个服务都会发生此错误。

 constructor(
    private userRepository: UserRepository,

    @InjectRepository(Workout) <--- Error
    private workoutRepository: Repository<Workout>,
  ) {}
{
  "compilerOptions": {
    "module": "CommonJS",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictBindCallApply": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "resolveJsonModule": true
  }
}

我收到以下错误: 当作为表达式调用时,无法解析参数装饰器的签名。 “未定义”类型的参数不可分配给“字符串 |”类型的参数符号'.ts(1239)

真不知道为什么会出现这个

typescript nestjs repository decorator
1个回答
0
投票

我已经使用

@Inject(forwardRef(() => Class))
引发了这个 lint 错误。

可以通过将

@nestjs/common
更新为
v9.3.0
来解决。

显然,这是 TypeScript v5 引入的问题。 “[它]对装饰器类型检查进行了一些收紧。”1

Inject
的工作原理:

export declare const Inject:
  (entity: Function) =>
    (target: object, key: string | symbol, index?: number) => void;

export class Foo {}

export class C {
  constructor(@Inject(Foo) x: any) {}
}

如您所见,

Inject
需要第二个参数,即
symbol
string

NestJS v9.3.0 在这个合并的 PR 下解决了这个问题:Constructor parameter decorators should allow undefined as the type of key #10959

© www.soinside.com 2019 - 2024. All rights reserved.