개발새발

Axios 타입 분석하기 본문

Typescript

Axios 타입 분석하기

비숑주인 2025. 5. 15. 16:45

1. Axios는 TypeScript를 지원하는가?

  • npmjs.com/axios에서 확인 가능.
  • TS 마크가 있으므로 별도의 @types/axios 설치 불필요.

2. Axios 설치 및 테스트 코드 작성

cd (tsbook 경로)
mkdir axios
cd axios
npm i axios@1.3.3
npx tsc --init

 

test.ts 코드 예시:

import axios from 'axios';

interface Post {
  userid: number;
  id: number;
  title: string;
  body: string;
}

(async () => {
  try {
    const res = await axios.get<Post>('https://jsonplaceholder.typicode.com/posts/1');
    console.log(res.data.userid);

    const res2 = await axios.post<Post>('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userid: 1,
    });
    console.log(res2.data.id);
  } catch (error) {
    if (axios.isAxiosError<{ message: string }>(error)) {
      console.log(error.response?.data.message);
    }
  }
})();

 

3. 타입 선언 진입점 찾기

  • node_modules/axios/package.json 확인:
"types": "index.d.ts",
"type": "module"

 

  • type은 ECMAScript 모듈 시스템을 의미하며, types는 타입 선언 파일 경로를 의미.

4. Axios 타입 구조 추적

① index.d.ts에서 export default:

declare const axios: AxiosStatic;
export default axios;
② AxiosStatic 확인:
export interface AxiosStatic extends AxiosInstance {
  create(...): AxiosInstance;
  isAxiosError: typeof isAxiosError;
  ...
}

 

③ AxiosInstance 확인:

export interface AxiosInstance extends Axios {
  <T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
  <T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
  defaults: ...;
}

 

④ 최종적으로 Axios 클래스에서 get 등 메서드 확인 가능:

export class Axios {
  get<T = any, R = AxiosResponse<T>, D = any>(
    url: string,
    config?: AxiosRequestConfig<D>
  ): Promise<R>;
  post<T = any, R = AxiosResponse<T>, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig<D>
  ): Promise<R>;
  ...
}

 

5. 제네릭 타입 분석

const res = await axios.get<Post>('...');
  • T: 응답 데이터 타입 → Post
  • R: 기본값 AxiosResponse<T> → AxiosResponse<Post>
  • D: 요청 데이터 타입 (GET에는 사용 안 함)

반환 타입:

Promise<AxiosResponse<Post>>

 

res.data의 타입은 Post

 

6. AxiosResponse 타입

export interface AxiosResponse<T = any, D = any> {
  data: T;
  status: number;
  statusText: string;
  headers: ...;
  config: InternalAxiosRequestConfig<D>;
  request?: any;
}

 

  • T: 서버로부터 받은 데이터 타입
  • D: 서버로 보낸 데이터 타입

7. AxiosRequestConfig와 InternalAxiosRequestConfig

  • AxiosRequestConfig<D>: 요청 설정 전반
  • InternalAxiosRequestConfig<D>: 내부적으로 확장된 설정 (headers 타입 변경됨)
export interface AxiosRequestConfig<D = any> {
  url?: string;
  method?: Method;
  data?: D;
  headers?: ...;
  ...
}

8. post 메서드에서 D 타입 추론

const res2 = await axios.post<Post>('...', {
  title: 'foo',
  body: 'bar',
  userid: 1
});
  • D 타입은 명시하지 않아도 data 객체로부터 자동 추론
  • 필요시 <T, R, D> 형태로 명시 가능하지만 생략해도 문제 없음

9. 에러 핸들링 타입

if (axios.isAxiosError<{ message: string }>(error)) {
  console.log(error.response?.data.message);
}

 

  • isAxiosError<T>: 에러 응답 데이터 타입을 명시 가능
  • error.response?.data의 타입이 { message: string }임을 보장
요소 설명
axios.get<T>() 서버 응답 타입 명시 (T)
axios.post<T>() 응답은 T, 전송 데이터는 자동 추론 (D)
AxiosResponse<T> 응답 전체 구조 (data, status, 등 포함)
AxiosRequestConfig<D> 요청 설정 타입 (data, headers, 등 포함)
isAxiosError<T> 에러 타입 가드, response.data의 타입 지정 가능