[ NestJS ] Argument type "PORT" is not assignable to parameter type KeyOf<K>

jwkwon0817·2023년 10월 14일
0

Web Back-end

목록 보기
22/26
post-thumbnail

NestJS에서 @nestjs/config의 ConfigService를 사용해서 설정 파일에 접근하려면 생성자에 주입해주는 방법으로 사용이 가능합니다.

하지만 main.ts에서 사용하기 위에서는 다른 방법을 사용해야합니다.

// main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
	const app = await NestFactory.create(AppModule);
	
	const configService = app.get(ConfigService);
	
	const port = configService.get('PORT');
	
	await app.listen(port);
	
	console.log(`NestJS server running on port ${ port }`);
}

bootstrap();

위와 같이 app.get()을 사용해서 .env 파일에 있는 값을 가져올 수 있지만 'PORT' 부분에 Argument type "PORT" is not assignable to parameter type KeyOf<K>라는 문구와 함께 빨간 줄이 그어집니다.

이를 해결하기 위해서는 app.get()에 제네릭을 사용해서 ConfigService 타입을 정해주면 됩니다.

// main.ts 일부
const configService = app.get<ConfigService>(ConfigService);

결론

const configService = app.get<ConfigService>(ConfigService);

configService.get('PROPERTY_NAME') // PROPERTY_NAME에 속성 값 입력
profile
SRIHS 119th SW

0개의 댓글