M:N 등록/조회 API 작성에서 Typescript 문제 질문드립니다.
안녕하세요.
제가 찾고 기다리던 내용의 강의라 매우 만족하며 수강하고 있는 수강생입니다! ㅎ
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
안녕하세요. endymion cheon님
문의주신 내용을 살펴본 결과, 먼저 result2의 담겨지는 데이터의 타입이 string이 아닌 것으로 보입니다. 따라서 이 부분부터 디버깅을 해보시길 바랍니다.
또한 타입을 지정하는 방법으로는 interface를 활용하는 방법이 있습니다. 아래의 링크를 확인하여 학습해 보시길 바랍니다. 감사합니다.
https://www.typescriptlang.org/docs/handbook/interfaces.html
0
답변 고맙습니다!
앗! 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);
}
그래프 ql 문서 사용할때 느낌표 남는거 어떻게 없애나요?
0
86
2
강의 전체 소스 코드를 받고싶습니다.
0
77
2
fontawesome 사용 문의
0
81
2
소스 코드 부탁드립니다~
0
87
2
깃 레포지터리 소스
0
87
2
커리큘럼12.css 정렬 에 나오는 과제 정답알고싶어요
0
74
2
10-01 Entity TypeOrmModule.forRoot 에 entities
0
89
3
강의 버전관련 문의입니다
0
104
2
Ubuntu 설치 관련
0
62
1
schema.gql 질문 드립니다.
0
51
1
서버 재실행시 Many to Many
0
102
3
input 관련 문의
0
90
2
Rest API 보다는 graphql이 주된 내용인데
0
134
2
강의 전체 소스코드 받을수있을까요?
0
156
1
도커볼륨 마운트 관련
0
127
2
findOne 타입스크립트오류
0
109
1
http => htrtps 호출 인증서 신뢰 오류
0
356
1
self-signed certificate in certificate chain 에러 발생
0
421
1
mongoose 설치 오류
0
143
1
특정 API, 특정 IP 허용 (단일경로에 CORS 활성화)
0
286
2
08-06
0
180
3
구조랑 패턴 관련해서 질문
0
126
2
mydocker
0
129
2
coolsms statuscode 2000 인데 전송안돼는 경우 확인.
0
156
1





