When I was working on a NestJS project, I was trying to write a test case for a service. But I encountered an error when trying to inject ZodAnyType
as a argument for the directive.
Setup
tsconfig.json
file was configured with strict: true
and strictNullChecks: true
.
// src/scehma.ts
import { z } from 'zod';
export const MySchema = z.object({
id: z.string(),
name: z.string(),
age: z.number(),
});
declare global {
export type MySchema = z.infer<typeof MySchema>;
}
// src/repo.d.ts
declare function InjectRepository(model: ZodTypeAny): any;
declare function retrieveRepoToken(model: string): any;
// src/app.service.ts
import { Injectable } from '@nestjs/common';
export class MyService {
constructor(
@InjectRepository(MySchema) private readonly myModel: MySchema,
private readonly myDependency: MyDependency) {}
myMethod() {
throw new Error('Method not implemented.');
}
}
Issue
When I tried to run the code with nest start
, there's was no error. But VSCode IDE will show Unable to resolve signature of method decorator when called as an expression. Argument of 'undefined' is not assignable to parameter of type 'string | symbol'.
error.
Therfore, in order to ignore the error, I added @ts-expect-error
directive above the line where the error occurred.
// src/app.service.ts
//...
// @ts-expect-error: no error when building
@InjectRepository(MySchema) private readonly myModel: MySchema,
//...
When I tried to run the code again with nest start
, I got another error Unused '@ts-expect-error' directive
error.
Solution
To solve this issue, I had to add @ts-ignore
directive instead of @ts-expect-error
directive. But first I need to allow @ts-ignore
comment in eslintrc.js
configuration.
// .eslintrc.js
module.exports = {
//...
rules: {
//...
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-expect-error': 'allow-with-description',
'ts-ignore': 'allow-with-description',
},
],
},
};
Now, I can use @ts-ignore
directive to ignore the error in IDE and able to build the code without any error.