Typescript 기초 (1) - Type 정의

Singsoong·2022년 6월 18일
0

Typescript

목록 보기
2/6

📌Props type 정의하기

  • Circle 컴포넌트에서 bgColor props를 전송하고 있다.
function App() {
  return (
    <>
      <Circle bgColor="teal" />
      <Circle bgColor="tomato" />
    </>
  );
}
  • bgColor props를 받은 Circle이다. 받은 bgColor에서 object의 type을 명시하지 않아 오류가 난다.
function Circle({ bgColor }){
  return <Container bgColor={bgColor} />;
}
  • 따라서, interface를 통해 받은 props의 type을 정의해주고 전달해야 한다.
interface CircleProps {
  bgColor: string;
}
  • 추가한 인터페이스를 bgColor에 할당한다.
function Circle({ bgColor }: CircleProps){
  return <Container bgColor={bgColor} />;
}

📌Components type 정의하기

  • 또한, styled-components인 Container도 type을 전달해주어야 한다.
interface ContainerProps {
  bgColor: string;
}

const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  border-radius: 100px;
`;
  • 이렇게 interface를 사용하게 되면 props. 입력 후 자동완성이 되므로 편리하다.

📌Object type 정의하기

const sayHello = (playerObj) => `Hello ${player.name}`;
  • playerObj 객체의 타입을 명시하지 않아 에러가 발생
  • 따라서,
interface PlayerShape {
  name: string;
  age: number;
}
  • interface를 이용해 type을 정의한다.
sayHello({name: "ryu", age: 26});
  • 이런식으로 작성 가능하다.
sayHello({name: "ryu", age: 26, weight: 70});
  • 이렇게 정의하지 않은 멤버를 작성하면 에러가 발생한다.
  • 코드 실행전에 에러를 확인할 수 있는 장점이 있다.

📌Optional Props

  • 위와 같이 Circle의 type을 명시한 뒤 아래와 같이 코드를 작성하면,
<Circle />
  • 필수로 요구되는 Props를 전달하지 않았기 때문에 오류가 뜨는것을 확인할 수 있다.
  • 여러 Circle 컴포넌트 중 어떤 것만 borderColor를 주고 싶은 상황이 생길 수 있다. 그럴 때 Optional Props를 사용하면 된다.
  • Optional Props는 type을 정의한 멤버명에 물음표(?)만 붙히면 된다.
interface CircleProps {
  bgColor: string; // 필수 Props 
  borderColor?: string; // borderColor는 있어도 되고, 없어도 되는 Props이다.
}
  • Circle 컴포넌트에게 borderColor props를 전달하는데, 전달하지 않는 컴포넌트는 undefined로 전달하게 된다.
  • 이때 ??를 이용하면 default value를 설정할 수 있다.
function Circle({ bgColor, borderColor }: CircleProps) {
  return <Container bgColor={bgColor} borderColor={borderColor ?? "blue"} />;
}
  • 전달받은 borderColor의 값이 undefined라면, "blue"를 할당하고, borderColor 값을 전달 받았으면 전달받은 값을 사용하라라는 코드이다.
  • default value를 할당하는 다른 방법도 있다.
<Circle bgColor="teal" />
<Circle bgColor="tomato" borderColor="red" text="hello"/>
  • 먼저, CircleProps에 text를 추가하고
interface CircleProps {
  bgColor: string;
  borderColor?: string;
  text?: string; // Optional props
}
  • Circle 컴포넌트에 전달받은 text를 정의할 때 text = "defalut text" 이런 식으로 코드를 작성하면 text props를 전달 받으면 전달받은 값을 text에 할당하고, 전달 받지 않으면 undefined이므로 default값인 "defalut text" 를 전달하게 된다.
function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
  return (
    <Container bgColor={bgColor} borderColor={borderColor ?? "blue"}>
      {text}
    </Container>
  );
}
  • 이것은 TS 구문이 아니라 ES6 JS syntax이다.

profile
Frontend Developer

0개의 댓글