aotoyae

[TS] 비동기 함수 & React에 타입스크립트 사용 : props 본문

TypeScript

[TS] 비동기 함수 & React에 타입스크립트 사용 : props

aotoyae 2024. 3. 6. 11:40

 

 

💡 비동기 함수에 타입스크립트를 사용해 보자.

 

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
후 : number

| undefined 가 나오는 건 useState 에 아무 값도 넣어주지 않아서! initailaState 를 정해주지 않아서!

 

이제 number 만 뜬다 ~

 

  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>;
}