• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

M:N 등록/조회 API 작성에서 Typescript 문제 질문드립니다.

23.01.24 10:17 작성 조회수 377

0

안녕하세요.

제가 찾고 기다리던 내용의 강의라 매우 만족하며 수강하고 있는 수강생입니다! ㅎ

products.service.ts 파일에서 create와 update 메서드 작성할 때 typescript 에러에 대해 질문드립니다.

products.service.ts 파일 create 메서드에서 productTags를 등록하는 과정에

const result2 = [] 부분을 const result2: string[]로 작성하면 await productRepository.save(...) 에서 No overload matches this call이 뜨고

update 메서드에서 updateProductInput에 UpdateProductInput로 타입을 지정하면 위와 마찬가지로 await productRepository.save(newProduct)에서 No overload matches this call이 뜹니다.

두 경우 모두 Type 'string' is not assignable to type 'ProductTag' 문제로

product.entity.ts에서는 productTag를 아래와 같이 등록하고

@Field(() => [ProductTag])

@JoinTable()

@ManyToMany(() => ProductTag, (productTags) => productTags.products)

productTags: ProductTag[];

 

createProduct.input.ts에서는 CreateProductInput에서 productTag를 아래와 같이 등록해서 발생하는 문제라고 추측했습니다.

@Field(() => [String])

productTags: string[];

두 경우 모두 타입을 지정하지 않고 any로 두면 문제는 사라지긴 합니다. any로 두고 사용할 수밖에 없는 것인지 아니면 타입 지정을 해서 사용하는 방법이 있는지 궁금합니다.

답변 1

답변을 작성해보세요.

0

angie님의 프로필

angie

2023.01.25

안녕하세요. endymion cheon님

문의주신 내용을 살펴본 결과, 먼저 result2의 담겨지는 데이터의 타입이 string이 아닌 것으로 보입니다. 따라서 이 부분부터 디버깅을 해보시길 바랍니다.

또한 타입을 지정하는 방법으로는 interface를 활용하는 방법이 있습니다. 아래의 링크를 확인하여 학습해 보시길 바랍니다. 감사합니다.
https://www.typescriptlang.org/docs/handbook/interfaces.html

답변 고맙습니다!

앗! result2이 ProductTag[] 타입이었는데 착각했었네요 ㅠㅠ

그리고 update 메서드에서 updateProductInput에 타입 지정했을 때 newProduct에서 나는 오류는 updateProductInput안의 productTags는 string이고 저장할 때는 ProductTag 타입이어서 그런 것 같습니다. create메서드에서 처럼 productTagRepository를 이용해서 저장했더니 해결되었습니다.

async update({ productId, updateProductInput }: ProductUpdateArgs) {

const prevProduct = await this.productRepository.findOne({

where: { id: productId },

});

const { productTags, ...updateProduct } = updateProductInput;

const newTags: ProductTag[] = [];

for (let i = 0; i < productTags.length; i++) {

const tagName = productTags[i].replace('#', '');

const prevTag = await this.productTagRepository.findOne({

where: { name: tagName },

});

if (prevTag) {

newTags.push(prevTag);

} else {

const newTag = await this.productTagRepository.save({ name: tagName });

newTags.push(newTag);

}

}

const newProduct = {

...prevProduct,

id: productId,

...updateProduct,

productTags: newTags,

};

return await this.productRepository.save(newProduct);

}