Language/Typescript
AxiosResponse<T> (Promise랑 뭐가 다른데?!)
Jaka_Park
2025. 5. 8. 15:12
타입스크립트로 프로젝트를 진행하던 중 에러가 발생했다.
타입 지정을 제대로 하지못해 발생했다.
밑에는 내가 겪은 TypeScript 에러다.
Type 'AxiosResponse<string, boolean>' is missing the following properties from type 'Promise<AxiosResponse<string, boolean>>': then, catch, finally, [Symbol.toStringTag]ts(2739)
const res: Promise<AxiosResponse<string, boolean>>
의미는 다음과 같다.
"야! AxiosResponse<string, boolean> 을
Promise<AxiosResponse<string, boolean>>라고 착각한거야!!!"
내가 착각한 부분은 다음과 같다.
- axios면 비동기니까 당연히 Promise 객체를 받아야하는거 아니야??
- 그럼 Promise도 써주고 AxiosResponse도 써주면 되는거 아니야??
결론
당연히 내가 틀렸다.
일단, 이 개념들은 TypeScript에서 axios 응답을 다룰 때 가장 핵심이 된다.
그러니 당장 알아보자!!
AxiosResponse<T> ?
- axios로 요청한 후 "받게 되는 실제 응답" 객체의 타입을 의미한다
- .data, .status, .headers 같은 응답 정보를 담고 있다
import type { AxiosResponse } from 'axios';
const res: AxiosResponse<{ message: string }> = {
data: { message: 'OK' },
status: 200,
statusText: 'OK',
headers: {},
config: {},
};
Promise<AxiosResponse<T>> ?
- axios 요청의 결과로 반환되는 Promise의 타입이다.
- 요청이 끝나면 AxiosResponse<T>를 resolve하는 Promise.
const resPromise: Promise<AxiosResponse<{ message: string}>> =
axios.get<{ message: string }>('/api/hello');
// 실제 응답을 얻으려면 await를 해야한다!
const res = await resPromise;
차이점
항목 | AxiosResponse<T> | Promise<AxiosResponse<T>> |
사용해야 할 때 | 응답을 다 받은 후 | axios 요청 결과를 받을 때 |
async/await 필요 여부 | 필요 없음 (이미 받은 상태다) | await or .then() 필수 |
타입 예시 | AxiosResponse<{ id: number }> | Promise<AxiosResponse<{ id: number}>> |
마무리
둘의 차이를 알았으니 또 프로젝트하러 가야지... 배우는건 늘 즐겁다.