[TIL] Day 55 : typeOrmModuleOptions 에러

Q·2024년 7월 1일

TIL

목록 보기
56/59

문제 발생

  • app.module.ts 파일

password 부분에서 에러 발생

const typeOrmModuleOptions = {
  useFactory: async (
    configService: ConfigService,
  ): Promise<TypeOrmModuleOptions> => ({
    type: configService.get('DB_TYPE'),
    host: configService.get('DB_HOST'),
    port: configService.get('DB_PORT'),
    username: configService.get('DB_USERNAME'),
    password: configService.get('DB_PASSWORD'),
    database: configService.get('DB_NAME'),
    entities: [Post],
    synchronize: configService.get('DB_SYNC'),
    logging: true,
  }),
  inject: [ConfigService],
};

해결

TypeScript와 NestJS에서 환경 변수를 설정할 때, configService.get() 메서드의 반환 타입이 string | undefined이기 때문에 타입 오류가 발생할 수 있다고 한다.

따라서 위와 같이 configService.get<string>('DB_PASSWORD') 와 같은 방식으로 타입 단언을 추가하여 configService.get() 메서드가 반환하는 값이 string 타입임을 TypeScript에 확실하게 알려주기 위해 타입 단언(type assertion)을 사용해야 한다.

다른 문제 발생

DB type을 적는 것도 하드코딩 같아서 .env 파일에서 관리를 하려고 했는데 애초에 TypeOrmModuleOptions에서 type이 될 수 있는 값을
'mysql', 'mariadb', 'postgres', ... 로 제한을 걸어놓은듯 하다. 이를 아우르는 타입 이름으로 해보려고 했지만
(<DatabaseType> with import { DatabaseType } from 'typeorm';)
여전히 에러가 발생했다.

해결

그래서 그냥 'mysql' 로 하드코딩하는 걸로 해결할 수밖에 없었다.

0개의 댓글