[TIL] 6/25 React + TS

yeseul·2024년 6월 25일

<TIL>

목록 보기
26/43

* 함수에서의 사용

// 함수
function sum(a: number, b: number): number {
  return a + b;
}

function objSum({ a, b }: { a: number; b: number }): string {
  return `${a + b}`;
}

* data fetching

// data fetching
// 방법 1 : Promise<>
async function getPerson(): Promise<Person[]> {
  const res = await fetch(`http://localhost:5008/people`);
  if (!res.ok) {
    throw new Error();
  }
  return res.json();
}

getPerson().then((res) => console.log(res[0].age));	// 바로 타입스크립트로 변경돼서 사용.

// 방법 2 : as any as
async function getPerson() {
  const res = await fetch(`http://localhost:5008/people`);
  if (!res.ok) {
    throw new Error();
  }
  return res.json() as any as Person[];
}

getPerson().then((res) => console.log(res[0].age));

* generic 제네릭

: 데이터의 타입을 일반화(generalize)=변수화 하는 것을 의미한다.

  • 타입을 생성할때 원하는 타입을 인자로 받아서 넣어준다.
type Generic<T> = {
    someValue: T;
}

type Test = Generic<string>;
function someFunc<T>(value: T) {}

✔️ 리액트에서의 활용

  • useState
    : useState<type>()
import { useState } from "react";

function App() {
  const [counter, setCounter] = useState<number>(1);
  const increment = () => {
    setCounter((prev) => 5);
  };
  return <div onClick={increment}>{counter}</div>;
}
  • props
function Parent() {
    const [count, setCount] = useState("");
    return <Child count={count}></Child>;
}

type Props = {
	count: sting;
}

function Child({count}: Props) {
    return <div>{count}</div>;
}

0개의 댓글