관리 메뉴

프로그래밍 삽질 중

[TS] Axios 타입 분석 및 Axios 타입 만들기(get, post, put, patch, delete) 본문

과거 프로그래밍 자료들/Javascript&typescript

[TS] Axios 타입 분석 및 Axios 타입 만들기(get, post, put, patch, delete)

평부 2022. 9. 21. 17:09

 

출처 : https://github.com/ZeroCho/ts-all-in-one

 

GitHub - ZeroCho/ts-all-in-one

Contribute to ZeroCho/ts-all-in-one development by creating an account on GitHub.

github.com

 

 

* 참고(url 및 method 방식들)https://jsonplaceholder.typicode.com/guide/

 

JSONPlaceholder - Guide

Guide Below you'll find examples using Fetch API but you can JSONPlaceholder with any other language. You can copy paste the code in your browser console to quickly test JSONPlaceholder. Getting a resource fetch('https://jsonplaceholder.typicode.com/posts/

jsonplaceholder.typicode.com

 

 

* Axios 타입분석(get, post, put, patch, delete) - typescript

▶ put, patch, delete는 "[리뉴얼] 타입스크립트 올인원 : Part2. 실전 분석편" 내에 내용 없음

▶ 문제점이 있다면 댓글로 알려주세요

import axios, {AxiosResponse} from "axios";

interface G { userId: number, id: number, title: string, body: string } 
interface P {}
interface data { title: string, body: string, userId: 1 }
interface P {}
interface data2 { id: number, title: string, body: string, userId: number }
interface PA {}
interface data3 { title : string }
interface D {}

(async () => {//getResponse, getResponse2 둘 다 상관 없음
  try {
    // 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>;
    // put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
    // patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;

    // delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
   
    const aGet = await axios.get<G, AxiosResponse<G>>('https://jsonplaceholder.typicode.com/posts/1')
    const aPost = await axios.post<P, AxiosResponse<P>, data>('https://jsonplaceholder.typicode.com/posts/1', 
    { title: 'foo', body: 'bar', userId: 1})
    const aPut = await axios.put<P, AxiosResponse<P>, data2>('https://jsonplaceholder.typicode.com/posts/1', 
    { id: 1, title: 'foo', body: 'bar', userId: 1,})
    const aPatch = await axios.patch<PA,AxiosResponse<PA>, data3>('https://jsonplaceholder.typicode.com/posts/1', {title: 'foo'})
    const aDelete = await axios.delete<D, AxiosResponse<D>>('https://jsonplaceholder.typicode.com/posts/1')

    console.log(aGet.data.id);
    console.log(aPost);
    console.log(aPut);
    console.log(aPatch);
    console.log(aDelete);
  } catch (error) {
    //isAxiosError(payload: any): payload is AxiosError;
    if(axios.isAxiosError(error)) {
       console.error(error.response?.data)
    }
  }
})();

 

 

* axios 타입 분석한 코드를 js로 변환할 경우 

더보기
import axios from "axios";
(async () => {
    var _a;
    try {
        // 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>;
        // put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
        // patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
        // delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
        const aGet = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
        const aPost = await axios.post('https://jsonplaceholder.typicode.com/posts/1', { title: 'foo', body: 'bar', userId: 1 });
        const aPut = await axios.put('https://jsonplaceholder.typicode.com/posts/1', { id: 1, title: 'foo', body: 'bar', userId: 1, });
        const aPatch = await axios.patch('https://jsonplaceholder.typicode.com/posts/1', { title: 'foo' });
        const aDelete = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
        console.log(aGet.data.id);
        console.log(aPost);
        console.log(aPut);
        console.log(aPatch);
        console.log(aDelete);
    }
    catch (error) {
        //isAxiosError(payload: any): payload is AxiosError;
        if (axios.isAxiosError(error)) {
            console.error((_a = error.response) === null || _a === void 0 ? void 0 : _a.data);
        }
    }
})();

 

 

* Axios 타입 만들기(get, post, put, patch, delete) - typescript

▶ put, patch, delete는 "[리뉴얼] 타입스크립트 올인원 : Part2. 실전 분석편" 내에 내용 없음

▶ 문제점이 있다면 댓글로 알려주세요

 

▶ void : 아무것도 반환하지 않는 함수에 사용하는 타입

자바스크립트: return 이 없는 함수가 undefined 를 반환함

▶ 타입스크립트는 return 이 없는 경우에는 void 를 사용 권장 

 

출처 : https://ujeon.medium.com/typescript-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EA%B8%B0%EC%B4%88-12-774010960945

 

[TypeScript] 타입스크립트 기초 — 12

함수 반환 타입 그리고 ‘void’

ujeon.medium.com

import axios, {AxiosResponse, AxiosError} from "axios";

interface G { userId: number, id: number, title: string, body: string } 
interface P {}
interface data { title: string, body: string, userId: 1 }
interface P {}
interface data2 { id: number, title: string, body: string, userId: number }
interface PA {}
interface data3 { title : string }
interface D {}

// 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>;
// put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
// patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
// delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
//isAxiosError(payload: any): payload is AxiosError;

// export class AxiosError<T = unknown, D = any> extends Error {
//     constructor(
//       message?: string,
//       code?: string,
//       config?: AxiosRequestConfig<D>,
//       request?: any,
//       response?: AxiosResponse<T, D>
//     );

interface Config<D = any> {
    method?: 'post' | 'get' |'put' | 'patch' | 'delete',
    url?: string,
    data?: D
}

interface AX {
    // R = AxiosResponse<T> 넣어도 그만 안 넣어도 그만
    // D는 필수 -> 선택으로 변경하고 싶으면? 기본값으로 변경하고 싶은 경우 D = any 사용 
    get: <T, R = AxiosResponse<T>>(url: string) => Promise<R>,
    post: <T, R = AxiosResponse<T>, D = any>(url: string, data?: D) => Promise<R>,
    put: <T, R=AxiosResponse<T>, D = any>(url: string, data?: D) => Promise<R>,
    patch: <T, R=AxiosResponse<T>, D = any>(url: string, data?: D) => Promise<R>,
    delete: <T, R = AxiosResponse<T>>(url: string) => Promise<R>,
    (config: Config): void,
    (url: string, config: Config): void
    isAxiosError: <T>(error: unknown) => error is AxiosError 
}

const ax: AX = axios;
(async () => {//getResponse, getResponse2 둘 다 상관 없음
  try {
    const aGet = await ax.get<G, AxiosResponse<G>>('https://jsonplaceholder.typicode.com/posts/1')
    const aPost = await ax.post<P, AxiosResponse<P>, data>('https://jsonplaceholder.typicode.com/posts/1', 
    { title: 'foo', body: 'bar', userId: 1})
    const aPut = await ax.put<P, AxiosResponse<P>, data2>('https://jsonplaceholder.typicode.com/posts/1', 
    { id: 1, title: 'foo', body: 'bar', userId: 1,})
    const aPatch = await ax.patch<PA,AxiosResponse<PA>, data3>('https://jsonplaceholder.typicode.com/posts/1', {title: 'foo'})
    const aDelete = await ax.delete<D, AxiosResponse<D>>('https://jsonplaceholder.typicode.com/posts/1')

    console.log(aGet.data.id);
    console.log(aPost);
    console.log(aPut);
    console.log(aPatch);
    console.log(aDelete);
  } catch (error) {
    //isAxiosError(payload: any): payload is AxiosError;
    if(axios.isAxiosError(error)) {
       console.error(error.response?.data)
    }
  }
})();

 

 

* axios 타입 만들기 코드를 js로 변환할 경우

더보기
import axios from "axios";
const ax = axios;
(async () => {
    var _a;
    try {
        const aGet = await ax.get('https://jsonplaceholder.typicode.com/posts/1');
        const aPost = await ax.post('https://jsonplaceholder.typicode.com/posts/1', { title: 'foo', body: 'bar', userId: 1 });
        const aPut = await ax.put('https://jsonplaceholder.typicode.com/posts/1', { id: 1, title: 'foo', body: 'bar', userId: 1, });
        const aPatch = await ax.patch('https://jsonplaceholder.typicode.com/posts/1', { title: 'foo' });
        const aDelete = await ax.delete('https://jsonplaceholder.typicode.com/posts/1');
        console.log(aGet.data.id);
        console.log(aPost);
        console.log(aPut);
        console.log(aPatch);
        console.log(aDelete);
    }
    catch (error) {
        //isAxiosError(payload: any): payload is AxiosError;
        if (axios.isAxiosError(error)) {
            console.error((_a = error.response) === null || _a === void 0 ? void 0 : _a.data);
        }
    }
})();

 

'과거 프로그래밍 자료들 > Javascript&typescript' 카테고리의 다른 글

[TS] Axios 타입 분석(get, post, error)  (1) 2022.09.21
[TS] flat  (1) 2022.09.20
[TS] bind  (1) 2022.09.20
[TS] Promise, Awaited  (1) 2022.09.20
[TS] (utility types) infer 타입 분석  (0) 2022.09.20