• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

제네릭을 활용한 Response 타이핑 7:40초 질문

22.09.21 13:08 작성 조회수 362

0

 

안녕하세요 강의를 듣다가 질문이 생겨 문의드립니다

axios.post 설명 중 interface Created {}가 이해되지 않아 질문 드립니다

import axios, {Axios, AxiosError, AxiosResponse} from "axios";

interface Post {userId: number, id: number, title: string, body: string}
interface Created {}
interface Data {title: string, body: string, userId: 1}

(async () => {
  try {
    const response = await axios.get<Post, AxiosResponse<Post>>(
      "https://jsonplaceholder.typicode.com/posts/1"
    );
    //post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
    const response2 = await axios.post<Created, AxiosResponse<Created>, Data>('https://jsonplaceholder.typicode.com/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1
    })
    console.log(response.data.id)
    console.log(response2)
  } catch (error) {
     if(axios.isAxiosError(error)) { //커스텀 타입가드
         // {message: "서버 장애입니다. 다시 시도해주세요"}
         console.error((error.response as AxiosResponse<{message: string}>)?.data.message)
     }
    }
  }
})();

 

[index.d.ts] 내의 axios.get의 경우 Post가 있어 타입을 확인할 수 있다는 것은 이해했습니다. 하지만 interface Post와 달리 interface Create는 빈 객체는 axios.post에서 무슨 역할인지 이해되지 않습니다.

개인적인 생각으로는 [index.d.ts]에서 T는 any니까 Create는 단순히 자리만 채우고 실제 타입 역할은 interface Data가 수행하는 것 같았습니다 제대로 이해한 게 맞나 싶어 문의드립니다

그리고 올려주신 강의 늘 잘 듣고 있습니다.

늘 어려운 부분, 이해되지 않는 부분을 쉽게 설명하셔서 감사합니다.

답변 1

답변을 작성해보세요.

1

Created는 AxiosResponse<T>에서 T입니다. 즉, post 요청에 대한 응답의 데이터 타입입니다.