실행해보기
$ 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>
}
'TypeScript' 카테고리의 다른 글
2024.3.8 기록 ( react-query의 useMutation을 커스텀훅으로) (0) | 2024.03.08 |
---|---|
2024.3.7 기록 (react-query 커스텀 훅과 타입) (1) | 2024.03.07 |
2024.3.5 기록 ( 타입스크립트의 유틸리티 타입 ) (0) | 2024.03.05 |
2024.3.4 기록 (타입스크립트의 시작) (0) | 2024.03.04 |