TypeScript - (2)Interface & Optinal props

Apeachicetea·2021년 11월 30일
1

TypeScript

목록 보기
2/5

Interface

어떻게 컴포넌트가 필요로 하는 props를 타입스크립트에게 설명할 수 있는지를 배운다.
그렇게 되면, 코드 실행 전 타입스크립트가 오류를 알려주게 된다.

interface는 object를 설명해주는 역활이다.
interface 안에다가 타입스크립트에게 object shape을 설명해준다

예시 코드

//App.tsx
import styled from "styled-components";
import Circle from "./Circle";

function App() {

  return (
    <div>
      <Circle bgColor="teal" />
      <Circle bgColor="tomato" />
    </div>
  );
}

export default App;

//Circle.tsx

//스타일컴포넌트의 인터페이스 적용
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){
  console.log(bgColor);
  return (
    <Container bgColor={bgColor} />
  );
}

export default Circle;

Required Props vs Optional Props

?만 추가해주면 된다.

  • 예시
interface CircleProps {
  bgColor: string;
  //required
  borderColor?: string;
  //optional
  text?: string;
  ////optional
}

?? (Null 병합 연산자: Nullish coalescing operator)

??앞에 값이 null이거나 undefined이면 오른쪽 값을, 그렇지 않으면 왼쪽 값을 반환하는 논리연산자

예시 코드

//App.tsx
import styled from "styled-components";
import Circle from "./Circle";

function App() {

  return (
    <div>
      <Circle bgColor="teal" borderColor="yellow"/>
      <Circle bgColor="tomato" text="Second"/>
    </div>
  );
}

export default App;


//Circle.tsx
import styled from "styled-components";

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

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

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

function Circle({ bgColor, borderColor, text = "default text" }: CircleProps){
  console.log(bgColor);
  return (
    <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
//스타일 컴포넌트 입장에서는 borderColor는 필수요소이고, Circle컴포넌트 입장에서는 borderColor는
//선택 요소이기 때문에 병합연산자를 사용해주지 않으면 오류가 나게 된다.
    
      { text }
    </Container>
  );
}

export default Circle;
profile
웹 프론트엔드 개발자

0개의 댓글