[TIL #44] Typescript 개인과제-2

차슈·2024년 6월 28일
0

TIL

목록 보기
45/70
post-thumbnail

폴더 구조

📦src
┣ 📂api
┃ ┗ 📜countriesApi.ts
┣ 📂components
┃ ┣ 📜CountryCard.tsx
┃ ┗ 📜CountryList.tsx
┣ 📂types
┃ ┗ 📜Country.ts

types- Country.ts

export interface Country{
   name:{
       common: string;
       official: string;
   };
   capital: string;
   flags: {
       png: string;
   };
}

해당되는 구조에 맞게 type 설정

api- CountriesApi

import axios, { AxiosResponse } from "axios";
import { Country } from "../types/Country";

const API = 'url';

export const PostCountries = async () : Promise<Country[]>=> {
    try{
        const response : AxiosResponse<Country[]>= await axios.get<Country[]>(API);
        return response.data;
    }catch(error){
        console.error("데이터 불러오기 에러", error);
        throw error;
    }
};

제너릭을 사용하여 axios가 반환하는 데이터 타입이 Country[]라는 것을 명시
이렇게 되면 axios.get이 반환하는 응답의 타입이 AxiosResponse<Country[]>가 된다.
이말은 즉, Axios가 반환하는 응답의 객체는 Country 타입의 객체들로 구성된 배열인걸 Typescript가 인지한다.

0개의 댓글