250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 리액트 훅
- Next 팀 프로젝트
- REACT
- 파이썬 반복문
- JavaScript
- 파이썬 for in
- 자바스크립트
- 리액트
- 파이썬 replace
- 타입스크립트 리액트
- 내일배움캠프 최종 프로젝트
- 타입스크립트 props
- 내배캠 프로젝트
- 파이썬 for
- 타입스크립트
- 내일배움캠프 프로젝트
- 코딩테스트
- 파이썬 slice
- 프로그래머스
- useState
- 한글 공부 사이트
- 내일배움캠프
- 리액트 공식문서
- 리액트 프로젝트
- useEffect
- tanstack query
- typeScript
- React Hooks
- 파이썬 enumerate
- 파이썬 딕셔너리
Archives
- Today
- Total
sohyeon kim
[TS] 비동기 함수 & React에 타입스크립트 사용 : props 본문
728x90
💡 비동기 함수에 타입스크립트를 사용해 보자.
fetchingData.ts
async function getPerson() {
const res = await fetch(`http://localhost:5008/people`);
if (!res.ok) {
throw new Error();
}
return res.json();
}
getPerson().then((res) => console.log(res));
ts-node fetchingData.ts 해보면 이렇게 데이터가 나온다.
그런데 지금 가져오는 값은 타입이 정해져 있지 않다. 바꿔보자!
🙋♂️ 첫 번째 방법
type Person = { id: number; age: number; height: number }; // 객체 타입을 정해주고
// 비동기 함수를 쓰고 있으니 반환값에 프로미스를 적고 제네릭으로 Person 지정
async function getPost(): Promise<Person[]> {
const res = await fetch(`http://localhost:5008/people`);
if (!res.ok) {
throw new Error();
}
return res.json();
}
getPost().then((res) => console.log(res));
그럼 타입이 바뀌어있고,
배열 관련 메서드들이 자동으로 뜨고 (cmd + i)
요소들을 바로 볼 수 있다.
🙋♂️ 두 번째 방법
type Person = { id: number; age: number; height: number };
async function getPost() {
const res = await fetch(`http://localhost:5008/people`);
if (!res.ok) {
throw new Error();
}
return res.json() as any as Person[]; // 여기 return 부분에 이렇게 적어줘도 똑같이 동작한다.
}
getPost().then((res) => console.log(res));
💡 React에 타입스크립트를 사용해 보자.
npx create-react-app my-first-ts-app --template typescript ~
그럼 js 파일들이 ts 로 설치된다.
✚ 에러를 예쁘게 보여주는 Pretty TypeScript Error 익스텐션
🙋♂️ 이제 진짜 써보자.
import { useState } from 'react';
export default function App() {
const [counter, setCounter] = useState<number>(); // number 로 지정
return <div>{counter}</div>;
}
| undefined 가 나오는 건 useState 에 아무 값도 넣어주지 않아서! initailaState 를 정해주지 않아서!
const [counter, setCounter] = useState(0); // 제네릭을 안쓰고 초기값에 숫자를 넣어주기만 해도
return <div>{counter}</div>;
number 로 뜨긴 하지만 명시적으로 해두고 싶다면 제네릭으로 쓰기❗️
export default function App() {
const [counter, setCounter] = useState<number>(0);
const increment = () => {
setCounter((prev) => prev++); // prev 를 살펴보면 알아서 number 가 지정되어 있다.
};
return <div onClick={increment}>{counter}</div>;
}
그런데 반환값을 문자열로 바꿔버리면 오류가 뜬다.
🙋♂️ props 에도 써보자 ~
import { useState } from 'react';
function Parent() {
const [count, setCount] = useState();
return <Child count={count}></Child>; // 평소와 같이 내려주는 중
}
function Child({ count }) { // 받는 중
return <div>{count}</div>;
}
export default Parent;
그런데 오류가 뜬다!
function Child({ count }: { count: number }) { // 받는 프롭에 타입을 설정해주자.
return <div>{count}</div>;
}
받는 쪽에서 타입을 정해줬지만 부모에선 undefined 라 에러가 뜬다.
function Parent() {
const [count, setCount] = useState(0); // 초기값을 넣어주면 된다 ~
return <Child count={count}></Child>;
}
😲 그런데 프롭스가 늘어나면 코드가 너무 길어질 것 같다!
function Child({ // ㅇㅁㅇ;;;;;
count,
double,
id,
des,
}: {
count: number;
double: number;
id: string;
des: string;
}) {
return <div>{count}</div>;
}
⬇️ 이럴 땐 아래처럼 타입을 빼서 넣어주면 된다.
type Props = {
count: number;
double: number;
id: string;
des: string;
};
function Child({ count, double, id, des }: Props) {
return <div>{count}</div>;
}
type Props = { // 프롭스가 적더라도 따로 타입을 빼두면 가독성이 좋다.
count: number;
};
function Child({ count}: Props) {
return <div>{count}</div>;
}
728x90
반응형
'TypeScript' 카테고리의 다른 글
[TS/React] props 유연하게 내리기 & Event Handler (0) | 2024.03.06 |
---|---|
[TS/React] TodoList 에 활용, props & children props (1) | 2024.03.06 |
[TS] 타입스크립트 활용 : 간단한 책 대여 프로그램 class (1) | 2024.03.06 |
[TS] 타입스크립트 활용 : 간단한 카페 주문 받기 프로그램 (2) | 2024.03.06 |
[TS] 타입스크립트 모듈 사용, 옵션 설정 & tsconfig/bases (0) | 2024.03.05 |