좌충우돌 개발자의 길

[TS] 타입스크립트 기초 본문

STUDYING/Typescript

[TS] 타입스크립트 기초

sustronaut 2022. 6. 12. 22:01

1. CRA로 만든 폴더에 TS 설치하기

npm install typescript @types/node @types/react @types/react-dom @types/jest @types/react-router-dom

 

2. 파일 확장자명 변경

.js -> .ts 

.jsx -> .tsx  

 

+ jsx vs js

//jsx
function App(){
	return (
    	<div>
        	Hello <b>react</b>
        </div>
    );
}

//jsx를 js로 변환 
function App(){
	return React.createElement("div", null, "Hello", React.createElement("b", null "react"));
}

 

 

3. type 적용

4. 에러 해결1

-> 기존의 word 객체를 사용하면서 id만 0으로 바꿔줌

 

5. 다른 파일에서도 특정 interface 사용하기

export
import 해주기

6. 에러 해결2

<> : 제네릭 - 파라미터로 어떤 타입을 사용할지 설정

//에러 
const {day} = useParams(); // === const { day } = useParams<{}>(); 빈 객체이다

//에러 해결
const { day } = useParams<{ day: string}>();

 

7. 에러 해결3

- form을 submit하는 이벤트 타입 설정

function onSubmit(e: React.FormEvent){...

 

8. 에러 해결4

- ref에 연결된 경우 input, select,, 무엇인지 파악해서 타입 설정

타입 설정

if (!isLoading && dayRef.current && engRef.current && korRef.current) { //dayRef.current, engRef.current, korRef.current가 없으면 실행x
      setIsLoading(true);
		
       // 이 value값들은 if문을 통해 안전하게 들어왔기 때문에 사용 가능함
      const day = dayRef.current.value; 
      const eng = engRef.current.value;
      const kor = korRef.current.value;

 

 

출처 : 코딩앙마