[React] TypeScript <수정예정>

Yoongja·2022년 4월 13일
0
post-thumbnail

TypeScript 란 :
strongly typed 언어로 type을 검사해주는 언어를 말한다. 즉, 자바스크립트에 타입을 부여한 언어를 뜻한다.

따라서 우리는 type을 적어줘야 한다.

const plus = (a:number,b:number) => a+b;
plus(1,1)
plus('w',1)

이결과 TypeScript는 코드가 실행되기전 오류를 반환하게 된다. 이렇게 함으로써 typescript는 개발자의 의도를 명확하게 코드로 기술하고 오류를 잡아낸다.

TypeScript 에게 React component를 설명하는 방법 :

어떻게 component가 필요로 하는 prop을 TypeScript에게 설명할 수 있는지를 배운다.

Interface란

object shape(객체모양)을 TypeScript에게 설명해주는 TypeScript의 개념이다.
이를 통해 object 가 어떤식으로 보일 지 설명해준다.

어느때와 같이 우리는 component를 만들어보자

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

우리는 Circle component가 필요로 하는 bcColor를 어떻게 Type Script에 알리나?

interface CircleProps {
  bgColor: string;
} //TypeScript에게 bgColor는 string이 되어야 한다고 설명해준다.

그리고 나서 우리는 props: CircleProps 로 추가해주면 된다.

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

이러면 typescript는 우리에게 필요한 부분을 명시하게 된다.

위의 코드에서 Container component한테도 prop을 전달하고 있다.

const Container = styled.div``;

Container 가 StyledComponent인 경우 어떻게 prop을 전달할까?
먼저 interface를 생성한다.

interface ContainerProps {
  bgColor : string;
}

그후,

const Container = styled.div<ContainerProps>

를 통해 styled component가 prop을 사용할 것을 명시해주면 된다.

지금까지 내용을 통해 interface가 proptypes와 비슷하다 느낄 수 있다. 맞다, 검사하는 것은 똑같지만 interface는 코드가 실행되기 전 검사를 해준댜는 것이 이점이다 !

만약 보내야 하는 prop이 optional이면 어떡할까?
다음 코드처럼 ?를 붙임으로써 optional을 지정해주면 된다.

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

이렇게 하면

이렇게 불평하던 것이

불만 하지 않는 것을 확인 할 수 있다 !

profile
Belief in the possibility

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN