본문 바로가기

TypeScript

2024.3.6 기록 (타입스크립트를 리액트에서 사용해보기)

실행해보기

$ ts-node <ts파일이름> 
  • 터미널에서 ts파일을 실행 할 수 있다.

 

비동기로 사용하기

type Character = {id : number; age: number; Role : string};

async function getCharacter() : Promise<Character>{
	const res  = await fetch ( 데이터.json);
	if (!res.ok) {
		throw new Error();
	}
	return res.json();
}

getCharacter().then((res) => console.log(res));
  • 비동기 함수는 선언부에 Promise<T> Promise로 감싸주게 되면 올바르게 실행이 된다.

 

 

useState에서 ts를 사용하는 방법

useState<T>(); //이렇게 직접 입력하는 방법과
useState(`초기값`) // 이렇게 initialState를 입력하면 그에 맞는 타입이 정해진다.

 

 

props로 넘겨주기

function Parent(){
	const [count, setCount] = useState(''); // 초기값을 정해준다.
	return <Child count ={count}></Child>
}

function Child({count} : {count : string}){ //props 옆에 추가해줄 수 있다.
	return <div>{count}</div>

//하지만 이렇게 inline으로 삽입할 경우 길어질 때 가독성이 나빠지는 경우가 존재한다.

//그럴땐 이렇게 별도로 분리해주고,
type Props ={
	count : string;
	double : string;
	id : string;
	des : string;
}

function Child ({count, double, id, des}: Props){ // 이렇게 적용해줄 수 있다!
	return <div>{count}</div>
}