The configuration documentation for NestJS provides an example of achieving type safety with the ConfigService
by using an interface named EnvironmentVariables
. This interface is then annotated during injection in the constructor like this:
constructor(private configService: ConfigService<EnvironmentVariables>) {...}
. However, I want to bind this interface permanently to the ConfigService
without having to remember to import and annotate it at every injection point. My attempt to do this through re-exporting a TypeScript version using extends
resulted in breaking the application. I suspect this happened because extending a service means it's no longer the original service, causing my extended version of ConfigService
to no longer be paired with the built-in ConfigModule
. What would be the best way to resolve this issue?
config.service.ts
import { ConfigService as NestConfigService } from '@nestjs/config';
interface EnvironmentVariables {
NODE_ENV: 'development' | 'production';
DATABASE_URL: string;
JWT_SECRET: string;
}
export class ConfigService extends NestConfigService<EnvironmentVariables> {}
users.module.ts
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
users.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '../config/config.service';
@Injectable()
export class UsersService {
constructor(private configService: ConfigService) {}
async example() {
return this.configService.get('JWT_SECRET');
}
}
error
[Nest] 16612 - 05/17/2023, 2:15:03 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument ConfigService at index [0] is available in the UsersModule context.
Potential solutions:
- Is UsersModule a valid NestJS module?
- If ConfigService is a provider, is it part of the current UsersModule?
- If ConfigService is exported from a separate @Module, is that module imported within UsersModule?
Error: Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument ConfigService at index [0] is available in the UsersModule context.