Search code examples
typescriptnestjsrepositorydecorator

NestJs Type Error - Argument of type 'undefined' is not assignable to parameter of type 'string | symbol'


Suddenly i get an type error when using the InjectRepository decorator in NestJs. This error happens in every service.

 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
  }
}

I get the following error: Unable to resolve signature of parameter decorator when called as an expression. Argument of type 'undefined' is not assignable to parameter of type 'string | symbol'.ts(1239)

I really don't know why this appears.


Solution

  • I've had this lint error raised using @Inject(forwardRef(() => Class)).

    It can be solved by updating @nestjs/common to v9.3.0.

    Apparently, this was an issue introduced by TypeScript v5. "[it] introduces some tightening on decorator type-checking."1

    How Inject worked:

    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) {}
    }
    

    As you can see, Inject requires a second argument that's either a symbol or a string.

    NestJS v9.3.0 has this solved under this merged PR: Constructor parameter decorators should allow undefined as the type of key #10959