Recently, I came across a tutorial at
Following the NestJS part of the tutorial, I encountered an error despite having code that seemed identical to the one in the tutorial.
[Nest] 94625 - 10/01/2024, 11:43:53 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the TrpcRouter (?). Please make sure that the argument Function at index [0] is available in the TrpcModule context.
Potential solutions:
- Is TrpcModule a valid NestJS module?
- If Function is a provider, is it part of the current TrpcModule?
- If Function is exported from a separate @Module, is that module imported within TrpcModule?
@Module({
imports: [ /* the Module containing Function */ ]
})
Below is the code snippet for that module:
import { Injectable, type INestApplication } from '@nestjs/common';
import type { TrpcService } from './trpc.service';
import { z } from 'zod';
import * as trpcExpress from '@trpc/server/adapters/express';
@Injectable()
export class TrpcRouter {
constructor(private readonly trpc: TrpcService) {}
appRouter = this.trpc.router({
hello: this.trpc.procedure
.input(z.object({ name: z.string().optional() }))
.query(({ input }) => {
return `Hello ${input.name ? input.name : 'World'}!`;
}),
});
async applyMiddleware(app: INestApplication) {
app.use(
'/trpc',
trpcExpress.createExpressMiddleware({ router: this.appRouter }),
);
}
}
export type AppRouter = TrpcRouter['appRouter'];
After various attempts, I found out that the root cause of the error was importing type rather than the whole module on this line:
import type { TrpcService } from './trpc.service';
By reverting it to the original tutorial version:
import { TrpcService } from './trpc.service';
the issue was resolved.
However, I am only using it as type and not as value:
constructor(private readonly trpc: TrpcService) {}
This raises the question - why does this happen? Why does it throw an error when I am just importing the type and not the value? Could it be related to how typescript functions within NestJS?
PS: Although there are similar questions out there, none seem to address this specific difference between type import and regular import.
PPS: During my search regarding type imports, I stumbled upon this potential answer to my query. Currently exploring it further: https://github.com/nestjs/nest/issues/5421