[TS] axios.post 타입 정해주기

wonny bong·2023년 10월 10일

axios.post를 사용할 때 타입을 정해보자!

오늘의 문제

axios.post에 url과 전송할 data를 넣는다. 그리고 응답을 콘솔에 찍어보려고 하니 빨간 줄이 생겼다.

axios
    .post('http://localhost:8000/users/signup', {
      account: idValue,
      password: pwValue,
      nickname: nameValue,
      email: emailValue,
    })
    .then((res)=>console.log(res))

아래와 같은 에러가 뜨는 걸로 봐서는 axios를 타입스크립트에서 사용하려면 요청 보내는 데이터와 응답받아서 오는 데이터의 타입을 지정해줘야 하는 것 같다.

에러 메세지

Property 'message' does not exist on type 'AxiosResponse<any, any>'.


해결

에러 메세지를 참고하여 AxiosResponse에 요청 타입, 응답 타입을 정해준다. 그러면 빨간 줄이 사라지고 타입이 정해진다. 다른 axios 인스턴스 메서드들도 비슷하게 정해주면 된다.

export interface SignUpType {
  account: string;
  password: string;
  nickname: string;
  email: string;
}

export interface SignUpRes {
  message: string;
}
axios
    .post<SignUpType, SignUpRes>('http://localhost:8000/users/signup', {
      account: idValue,
      password: pwValue,
      nickname: nameValue,
      email: emailValue,
    })
    .then((res)=>console.log(res))

axios 공식문서

profile
Web Frontend Programmer

0개의 댓글