TypeORM과 Typescript를 이용하여 MySQL에서 데이터를 추출할 때 정렬 기준을 변수로 사용하려고 하니 아래와 같은 오류가 발생하였다.
// paginationInputDto.dto.ts
export class PaginationInputDto {
@IsString()
sort: string; // 'ASC: 오름차순, DESC: 내림차순'
}
const sort = paginationInputDto.sort;
// 쿼리문
const products = await this.productRepository.createQueryBuilder('product')
.orderBy("price", sort) // 여기 sort에서 에러 발생
Argument of type 'string' is not assignable to parameter of type '"ASC" | "DESC"'
orderBy 에는 ASC 또는 DESC 만 가능하기에 'sort' 변수에도 이 두개의 단어외에는 다른 값들이 들어오지 못하도록 방지 해야하는데 그런 prevention 없이 string으로만 type을 정의해주니 마음에 안들었나보다.
type sort = 'ASC' | 'DESC'; // typeorm 정렬
export class PaginationInputDto {
@IsString()
sort: sort; // 'ASC: 오름차순, DESC: 내림차순'
}
type 을 이용하여 새로 정의한 후에 sort에 적용시킴으로서 해결하였다.