#들어가며

서버 쪽 글에서 모든 API 응답을 { success, data, ... } 형식으로 통일했다. 그 짝으로 프론트에는 이 형식을 벗겨주는 Axios interceptor가 있다. 호출부마다 response.data.data를 파는 대신, interceptor가 성공이면 data만 돌려주고 실패면 ApiError를 던진다.

typescript
publicApi.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (isApiResponse(data)) {
      if (data.success) {
        return data.data; // 알맹이만 반환
      } else if (isApiErrorResponse(data)) {
        throw new ApiError(data.message, data.code);
      }
    }
    return response.data;
  },
  (error: AxiosError<ApiErrorResponse>) => {
    if (error.response?.data && isApiErrorResponse(error.response.data)) {
      throw new ApiError(error.response.data.message, error.response.data.code);
    }
    throw new ApiError(
      error.message || "An unknown error occurred.",
      error.response?.status || 500,
    );
  },
);

런타임은 의도대로 동작한다. 그런데 API 함수를 쓰는 순간 TypeScript가 막아선다.

typescript
login: async (request: LoginRequest): Promise<LoginResponse> => {
  return publicApi.post<LoginResponse>("/api/v1/auth/login", request);
  // Type 'AxiosResponse<LoginResponse>' is not assignable to type 'LoginResponse'
},

#타입과 런타임이 다른 말을 한다

Axios의 타입 정의에서 post<T>()의 반환은 Promise<AxiosResponse<T>>다. 그런데 우리 interceptor는 그 안에서 data.data를 꺼내 T를 돌려주도록 런타임 동작을 바꿔놨다. interceptor의 변환은 타입 시스템 밖에서 일어나는 약속이라, TypeScript는 여전히 원래 타입 정의를 믿는다. 같은 코드를 세 가지 타입 전략으로 비교해보자.

as Promise<LoginResponse> 캐스팅은 통과하지만 두 가지가 걸린다. API 함수가 늘어날 때마다 반복되고, 캐스팅은 컴파일러를 설득하는 게 아니라 입을 막는 행위라 interceptor 동작이 바뀌어도 아무도 알려주지 않는다.

답은 거짓말을 한 곳에서 진실로 정정하는 것이다. 인스턴스의 타입을 우리 interceptor의 실제 동작에 맞게 재정의한다.

typescript
interface ApiInstance extends AxiosInstance {
  get<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
  post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T>;
  put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T>;
  patch<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T>;
  delete<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
}

export const publicApi = axios.create({ ... }) as ApiInstance;

런타임 코드는 한 줄도 안 바뀐다. 바뀌는 건 선언뿐이고, 이제 모든 호출부에서 post<LoginResponse>()가 Promise<LoginResponse>로 추론된다. interceptor가 런타임 계약을 바꿨으면 타입 계약도 같은 곳에서 같이 바꿔주는 것까지가 구현이라는 게 이 단계의 결론이었다.

곁들여 둘. 응답이 정말 우리 형식인지 확인하는 type guard(isApiResponse)는 외부 프록시 에러나 비표준 응답이 끼어들 때의 안전망이고, 모든 실패가 ApiError 하나로 수렴하니 React Query의 onError는 instanceof ApiError 분기 하나로 메시지와 코드를 다룬다.

#2막: 벗기는 편의가 버린 것

이 구조로 한참을 잘 쓰다가, 목록 API에 pagination이 들어오면서 문제가 드러났다.

json
{
  "status": true,
  "data": [ ... ],
  "pagination": { "pageNumber": 0, "totalPages": 12 }
}

interceptor는 data.data만 돌려주니, pagination은 호출부에 도달하기 전에 버려진다. 페이지네이션 UI를 만들 방법이 없다.

"알맹이만 주는 편의"는 알맹이 외의 모든 것을 버리는 결정이기도 했다. 응답에 메타데이터가 없던 시절에는 공짜 같던 편의가, 메타데이터가 생기는 순간 손실이 된 것이다. 그래서 interceptor가 검증과 에러 변환만 하고 전체 응답을 반환하도록 되돌렸다.

typescript
// interceptor: 검증/에러 변환만, 추출은 안 한다
if (data.status) {
  return data; // ApiResponse<T> 전체
}

// 호출부: 필요한 것을 직접 꺼낸다
login: async (request: LoginRequestDTO): Promise<LoginResponseDTO> => {
  const response = await publicApi.post<LoginResponseDTO>("/api/v1/auth/login", request);
  if (!response.data) {
    throw new Error("Login response data is missing");
  }
  return response.data;
},

호출부에 추출 한 줄이 늘었지만, pagination이 필요한 곳은 response.pagination으로 접근하고, data가 옵셔널이 되면서 "성공인데 본문 없음" 같은 변칙도 타입이 강제로 처리하게 만든다.

타입 쪽에도 후속 수정이 하나 따라왔다. 반환 타입을 Promise<ApiResponse<T>>로 바꾸려니 extends AxiosInstance 방식이 원본 시그니처와 충돌해서, 독립 인터페이스로 필요한 멤버만 명시하는 형태로 바꿨다.

typescript
interface ApiInstance {
  get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
  post<T>(
    url: string,
    data?: unknown,
    config?: AxiosRequestConfig,
  ): Promise<ApiResponse<T>>;
  // ...
  defaults: AxiosInstance["defaults"];
  interceptors: AxiosInstance["interceptors"];
}

상속 오버라이드는 원본과 호환되는 방향으로만 허용되는데, AxiosResponse<T>를 T로 좁히는 것은 우연히 통과했고 ApiResponse<T>로 바꾸는 것은 충돌했다. 어차피 원본 타입과 다른 말을 할 거라면 상속보다 독립 선언이 정직하다.

#두 시기의 정리

1기: data 추출2기: 전체 반환
호출부 코드가장 깔끔data 추출 한 줄 추가
pagination 등 메타데이터접근 불가접근 가능
data 누락 같은 변칙런타임에서 발견옵셔널 타입이 강제 처리
에러 일원화 (ApiError)유지유지

1기가 틀렸다기보다, 응답에 메타데이터가 없다는 전제가 깨지면서 맞는 답이 바뀌었다. interceptor에서 무엇을 벗길지는 "지금 응답에 무엇이 있는가"가 아니라 **"앞으로 응답에 무엇이 생길 수 있는가"**를 기준으로 정하는 게 두 번 고치지 않는 길이었다.

#핵심 정리

  • interceptor의 응답 변환은 타입 시스템 밖의 런타임 약속이다. 변환을 넣었으면 인스턴스 타입 재정의로 타입 계약도 같은 곳에서 맞춘다. 호출부 캐스팅 반복은 컴파일러의 입을 막는 것일 뿐이다
  • type guard로 응답 형식을 런타임 검증하고, 모든 실패를 ApiError 하나로 수렴시키면 호출부 에러 처리가 instanceof 분기 하나로 끝난다
  • data만 추출하는 interceptor는 pagination 같은 메타데이터를 버리는 결정이다. 메타데이터가 생길 수 있다면 전체 응답 반환 + 호출부 추출이 유연하다
  • 원본과 다른 시그니처가 필요하면 extends 오버라이드보다 독립 인터페이스가 정직하고 충돌도 없다

#References