일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 웹 게임을 만들며 배우는 리액트
- ReactDOM.render is no longer supported in React 18. Use createRoot instead
- spring-boot
- 모두의 파이썬
- Spring-Framework
- 노드에 리액트 추가하기
- DB Browser
- 타자 게임 만들기
- 자바스크립트
- Colaboratory 글자 깨짐
- JS 개념
- Python
- You are importing createRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client"
- 인프런
- intellij
- 따라하며 배우는 노드 리액트 기본 강의
- vs code 내 node
- node.js로 로그인하기
- googleColaboratory
- 거북이 대포 게임
- props
- intllij 내 Bean을 찾지 못해서 발생하는 오류
- Do it 자바스크립트 + 제이쿼리 입문
- react
- node.js 설치
- 리액트
- 계산맞추기 게임
- Concurrently
- react오류
- 모던자바스크립트
- Today
- Total
프로그래밍 삽질 중
[TS] Axios 타입 분석 및 Axios 타입 만들기(get, post, put, patch, delete) 본문
[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 를 사용 권장
[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 |