// 함수
function sum(a: number, b: number): number {
return a + b;
}
function objSum({ a, b }: { a: number; b: number }): string {
return `${a + b}`;
}
// 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));
: 데이터의 타입을 일반화(generalize)=변수화 하는 것을 의미한다.
type Generic<T> = {
someValue: T;
}
type Test = Generic<string>;
function someFunc<T>(value: T) {}
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>;
}
function Parent() {
const [count, setCount] = useState("");
return <Child count={count}></Child>;
}
type Props = {
count: sting;
}
function Child({count}: Props) {
return <div>{count}</div>;
}