TypeScript 정리 -1 & axios vs fetch

박경현·2024년 10월 30일

이번에 Next js로 프로젝트를 계속 만들면서 어떤걸 가장 많이 사용했나 생각해봤는데
바로 fetch를 가장 많이 사용했습니다.
역시 비슷하게 axios로 api호출도 하면서 사용했었는데요.

하면서 둘의 차이가 무엇이고 어떤 장단점이 있는지 분석했습니다 + TS정리

Axios vs Fetch

axios와 fetch 둘 다 HTTP통신을 위한 js라이브러리로 서버로부터 데이터를 가져올 수 있습니다.

axios의 특징

  • axios는 json을 자동으로 적용해서 response객체를 바로 반환
  • axios는 data를 바로 전달
  • import해줘야함

fetch의 특징

-import 필요없음, React Native의 경우 업데이트가 잦은데 이때 라이브러리가 업데이트 속도를 따라오는지 걱정할 필요가 없음

  • 지원하지 않는 브라우저가 존재
  • fetch는 promise자체를 반환해서 json으로 반환을 해줘야함

axios의 GET과 POST

//get
axios.get('/api/users')
	.then(response => {
    	console.log(response.data);
    })
    .catch(error => { console.error(error); });
    
// post
axios.post('/api/users', { name: 'john', age: 25})
	.then(response => {
    	console.log(response.data);
    })
    .catch(error => { console.error(error); });

fetch의 GET과 POST

// get
fetch('/api/users')
	.then(res => res.json())
    .then(data => { console.log(data); 
	})
	.catch(error => { console.error(error); });
    
// post
fetch('/api/users', {
	method: 'POST',
    headers: { 'Content-Type': 'application/json'},
    body: JSON.stringify({ name: 'john', age: 26})
})
	.then(res => res.json())
    .then(data => { console.log(data); 
	})
	.catch(error => { console.error(error); });

Typescript 정리

Next JS를 사용하는데 기본을 TS를 사용하다가 npm run build를 할때마다 매번 타입오류가 꼭 떠서
완전히 정리를 한번 하게 되었습니다.

//tsconfig.json
{
  "compilerOptions": {
    "target": "es5", // 컴파일된 코드가 어떤 환경에서 실행될지 정의 es6면 화살표 함수 가능!
    "module": "commonjs", // 컴파일된 코드가 어떤 모듈시스템을 사용할지, 
    // export default sample -> exports.default = helloworld로 변환
    "strict": true, // 모든 타입 체킹 옵션을 활성화
    "esModuleInterop": true,
    "outDir": "./dist" // 컴파일된 파일들이 저장되는 경로를 지정가능
  }
}

// 기본 변수
const message: string = "hello world";
let cout : number = 0; // 숫자
count += 1;
count = '갑자기 문자열' // 이러면 에러!

const messages: string[] = ['heelo', 'wrold'];
messages.push(1); // 안됨

let mightBeUndefined: string | undefined = undefined; // string일수도 있고 undefined도 가능
let color: 'red' | 'orange' | 'yellow' = 'red';
color = 'green'; //에러!!

// 함수
function sum(x: nuber, y: number): number | void {
	return x + y;
}
sum(1,2);


// 인터페이스
// 클래스가 가져야할 요구사항을 설정
interface Shape {
	getArea(): number; // Shape interface에는 getArea함수 필요
}

class Circle implements Shape {
	constructor(radius: number) {
		this.radius = radius;
	}
	
	getArea() {
		return this.radius * this.radius * Math.PI;
	}
}

class Rectangle implements Shape {
	constructor(private width: number) {
		this.width = width;
	}
	getArea() {
		return this.width;
	}
}

const circle = new Circle(5);
const rectangle = new Rectangle(10);

console.log(rectangle.width) // 이러면 오류!


// 일반 객체를 interface를 사용해서 타입을 지정
interface Person {
	name: string;
	age? :number; // age를 넣어도 되고 안넣어도 됨
}
interface Developer extends Person {
	skills: string[];
}

const expert: Developer = {
	name: '김개발',
	skills : ['js', 'html' ,'css']
};

const people: Person[] = [expert];

// type - 특정 타입에 별칭을 붙이는 용도
type Person = {
	name: stirng;
	age? : number;
}

type People = Person[]; // Person[] 를 이제 앞으로 People 이라는 타입으로 사용 할 수 있습니다.
const people: People = [person, expert];

type Color = 'red' | 'orange' | 'yellow';
const color: Color = 'red';
const colors: Color[] = ['red', 'orange'];


// Generics - 함수, 클래스. 인터페이스 타입을 사용하게 될때 어러종류의 타입에 대해 호환
function merge<A, B> (a: A, b: B): A & B {
	return {
		...a,
		...b
	};
}

const merged = merge({foo: 1}, {bar: 1});

interface Items<T> {
	list: T[];
}
const items: Items<string> = {
	list: ['a', 'b']
};
const items2: Items<number> = {
	list: [44, 55]
};

profile
SW로 문제를 해결하려는 열정만 있는 대학생

0개의 댓글