axios에서 TypeScript를 사용하여 GET 요청을 보낼 때, 응답 타입을 정의하려면 제네릭을 사용할 수 있다.
제네릭을 지원한다.
axios GET 요청에 TypeScript 제네릭을 사용하는 방법의 예입니다:
응답 타입 정의하기
먼저, 응답 데이터의 타입을 정의
interface UserResponse {
id: number;
name: string;
email: string;
// 기타 필요한 필드들...
}
axios GET 요청에 제네릭 사용하기
제네릭을 사용하여 axios GET 요청을 보내면, 응답 데이터에 대한 타입 안전성을 얻을 수 있다.
import axios from 'axios';
axios.get<UserResponse>('https://api.example.com/users/1')
.then(response => {
// 여기에서 'response.data'는 'UserResponse' 타입입니다.
console.log(response.data.name); // name에 접근하는 것은 안전합니다.
})
.catch(error => {
console.error('Error fetching user:', error);
});
프로젝트에서 예시
axios로 받아온 데이터는 아래와 같은 형식
필요한 부분은 data.response.body.items.item 데이터
제네릭으로 타입 가드 해줄 데이터의 인터페이스를 만들어준다.
export interface IRestAPIData {
response: {
body: {
items: {
item: IRestDate[];
};
};
};
}
axios get 요청 하는 부분에 제네릭으로 위에서 만들어준 타입을 넣어준다.
function fetchRestDate() {
const API_URL = `http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo`;
return axios.get<IRestAPIData>(
API_URL +
"solYear=2023&numOfRows=100&ServiceKey="
);
}
api로 받아온 데이터가 타입가드가 작동하면서 이터러블한 데이터로 인지하고 반복문을 돌릴 수 있다.
async function fetchAPI() {
const response = await fetchRestDate("getRestDeInfo");
console.log(response);
const restDates = response.data.response.body.items.item;
const mapRestDates = restDates.reduce<{
[key: string]: IRestDate;
}>((acc, cur) => {
acc[cur.locdate] = cur;
return acc;
}, {});
console.log(mapRestDates);
}
'타입스크립트' 카테고리의 다른 글
타입스크립트 interface 인덱서블 타입 (0) | 2024.03.12 |
---|---|
타입스크립트란? (0) | 2024.03.10 |
ts-node로 타입스크립트 파일 바로 실행 (0) | 2024.03.04 |
타입스크립트 declare 사용법 (0) | 2024.03.01 |
타입스크립트 타입 (0) | 2023.08.30 |
타입스크립트에서 axios API 제네릭으로 타입 넣어주기