TYPESCRIPT를 알아보자

초연2e·2022년 9월 20일
0

MUTSA_Front.archive

목록 보기
2/16

✍️ typescript

Javascript를 기반으로 만들어진 똑똑한 언어
코드가 실행되기 전에 오류를 알려줌!

ex) 변수 이름에 오타, 존재하지 않는 변수 등등...

설치 (두가지 방법~!)
1. npx create-react-app ~앱이름~ --template typescript
2. yarn create react-app ~앱이름~ --template typescript


우리는 styled-components를 사용할거니까

npm i --save-dev @types/styled-components

를 해줘야합니당

이대로 안해주면 typescript는 styled-components가 무엇인지 몰라서 오류가 뜰 것임,,,




📌 interface

typescript에게 object의 타입을 설명해주기 위해 사용됨 (변수, 함수, 클래스)

import styled from "styled-components";

const Container = styled.div``;

function Circle({bgColor}){
	return <Container/>;
}

export default Circle;

이런 코드가 있다고 해보자.
typescript는 {bgColor}에 오류메세지를 띄운다.
bgColor에 대한 정의가 내려져있지 않기 때문!


우리는 interface를 이용해서 bgColor의 타입정의를 해준다.

import styled from "styled-components";

const Container = styled.div``;

interface CircleProps{
  bgColor: string;
}

function Circle({bgColor}:CircleProps){
	return <Container/>;
}

export default Circle;

CircleProps에서 bgColor의 타입이 string이라고 설명해주었다.
그 후 bgColor의 타입이 CircleProps의 object라는 것을 {bgColor}:CircleProps의 형태로 typescript에게 알렸다.

이러면 에러 없이 잘 넘어가게 됨~!


import styled from "styled-components";

interface ContainerProps{
  bgColor: string;
}

const Container = styled.div<ContainerProps>`
	width: 200px;
	height: 200px;
	background-color: ${props=>props.bgColor};
	border-radius: 100px;
`;

interface CircleProps{
  bgColor: string;
}

function Circle({bgColor}:CircleProps){
	return <Container bgColor={bgColor}/>;
}

export default Circle;

그리고 추가로 Circle에서 props로 받아온 bgColorContainer의 props로 넘겨주었다.

이 때 ContainerbgColor의 타입을 모르기때문에 ContainerContainerProps라는 interface를 만들어서 bgColor의 타입정의를 해준다.


이렇게 하면 Circle과 Container가 받는 props에 대해 typescript에게 잘 설명하고 있는 것이기 때문에 에러가 뜨지 않음🤭🕺



📌 Optional Props

interface 선언 시

...
interface CircleProps{
  bgColor?: string;
}
... 

위와 같이 변수이름?:변수타입; 형식으로 정의한다면 Optional Props가 되어 props값이 정의되지않아도 에러메세지가 뜨지 않게된다.



📌 Default Props

...
interface ContainerProps{
  bgColor:string;
  borderColor:string;
}

interface CircleProps{
  bgColor: string;
  borderColor?: string;
}
  
function Circle({bgColor, borderColor}: CircleProps){
	return <Container bgColor={bgColor} borderColor={borderColor ?? white}/>
}
... 

borderColor={borderColor ?? white}를 해주면 borderColor가 선언되지 않았을 때 기본값으로 white가 borderColor가 된당~.




✍️ State

typescript에서는 state 사용시에도 타입에 주의해야한다.

예를 들어

const [counter, setCounter] = useState(0);
setCounter(2);

라는 코드가 있다고 하자.
이 코드는 아무 문제가 없고 에러메세지도 뜨지 않는다.

const [counter, setCounter] = useState(true);
setCounter(2);

그러나 이 코드는 counter에 에러메세지가 뜰 것이다.
counter의 타입은 boolean인데 setCounter에서는 int를 주었기 때문이다.
state의 타입은 계속 유지되어야한다.
(아주 극소수 제외)




✍️ Forms

Javascript는 form의 event타입을 지정해주지 않아도 사용 가능하지만, 엄격한 Typescript는 event가 어디서 발생하는지 타입을 지정해주어야함

...
function App(){
	const [value, setValue] = useState("");
	const onChange = (event: React.FormEvent<HTMLInputElement>)=>{
  	
    const {
    	currentTarget: {value},
    } = event;
      
    setValue(value);
  };
  
  const onSubmit = (event: React.FormEvent<HTMLFormElement>)=>{
  	event.preventDefault();
    console.log("hello", value);
  };
  
  return(
  ...
  );
}

이제 event는 React.FormEvent 내의 모든 메서드를 사용할 수 있게된다. 이제 그 이벤트의 모든 속성에 대해 자동완성기능이 가능해진다~ wow~~~

event: React.FormEvent<HTMLFormElement>

는 일종의 패턴이라고 보면 된다고 함!


참고로 만약 버튼에 onClick을 주는데 그 버튼이 form 안에 있는 버튼이 아니라면?
React.FormEvent가 아니라 React.MouseEvent가 될것임..~~😶‍🌫️😶‍🌫️

profile
프론트로 멋쟁이되기 대장정,,

0개의 댓글