so woon!

[TYPESCRIPT] optional props 본문

Typescript/개념정리

[TYPESCRIPT] optional props

xowoony 2023. 3. 31. 13:02

학습일 : 2023. 03. 31


interface를 만들면 반드시 required가 되어서 꼭 작성해주어야 하는데

(작성해주지 않으면 빨간줄이 뜨게 됨.)


그렇게 하고 싶지 않다면?
즉, 선택적으로 사용하고 싶다면 어떻게 해야할까?

 

바로 optional props로 만들면 되는데

적용방법은 아래와 같다.

 

 

 

<Circle.tsx>

이런식으로 interface 작성시

선택적으로 사용하고 싶은

borderColor옆에 ?를 붙여주면 된다.

interface CircleProps {
  bgColor: string; // required. 필수적으로 사용해야함.
  borderColor?: string; // optional. 사용해도 되고 안해도 됨.
}

 


전체코드

<Circle.tsx>

Container 컴포넌트 styled-component 정의해준 부분에서

작성한 css 속성들에는 optional props 여부를 표시하지 않는다.

optional props여부는 interface에서 해주면 된다.

아래 코드에서는 interface가 두개(ContainerProps, CircleProps) 인데

optional props를 좀 더 이해하기 쉽기 때문에 잠시 그렇게 만들어 놓은 것이다.

원래는

ContainerProps interface 작성 부분을 다 지우고

Container styled-component 부분에

const Container = styled.div<CircleProps> 의 형태로 작성해주면 된다.

 

아래 Circle Props 작성 부분에서

Container 컴포넌트 리턴시

borderColor={borderColor ?? "yellow"}

의 의미는 borderColor는 사용자가 입력한 color를 따르겠지만

입력을 해주지 않는다면 (undefined) yellow를 기본값으로 설정하겠다는 뜻이다.

import styled from "styled-components";
// interface
interface ContainerProps {
  bgColor: string; // CircleProps 상태랑 똑같이 만들어주어야 함.
  borderColor?: string; // CircleProps 상태랑 똑같이 만들어주어야 함.
}

interface CircleProps {
  bgColor: string; // required. 필수적으로 사용해야함.
  borderColor?: string; // optional. 사용해도 되고 안해도 됨.
}

// styled-component
const Container = styled.div<ContainerProps>`
  width: 5rem;
  height: 5rem;
  background-color: ${(props) => props.bgColor};
  border-radius: 100px;
  border: 0.5rem solid ${(props) => props.borderColor};
   // css에서 borderColor는 optional 상태가 아니다. optional 표시는 interface에서!
`;


// Circle Props
// bgColor의 타입은 CircleProps의 오브젝트다 라고 말해주고 있는격
// borderColor를 styled-component인 Container로 보내준다.
// borderColor는 optional이다. 위 interface에서 그렇게 정의해줬기 때문
// borderColor={borderColor ?? "yellow"} 의 뜻
// 사용자가 입력한 color를 따르겠지만, undefined면 yellow로 설정하겠다는 뜻.
function Circle({ bgColor, borderColor }: CircleProps) {
  return <Container bgColor={bgColor} borderColor={borderColor ?? "yellow"} />;

}

export default Circle;

 

 

<App.tsx>

여기서 두개의 <Circle /> 이 있는데

하나에는 bgColor, borderColor 모두 있고

나머지 하나에는 borderColor가 빠져있다.

위 Cirlce.tsx 파일에서 interface 작성시

borderColor 를 optional props로 만들어주지 않았다면

분명 에러가 났을 것이다.

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

function App() {
  return (
    <div>
      <Circle bgColor="teal" borderColor="black" />
      <Circle bgColor="red" />
    </div>
  );
}

export default App;

 

 

 

실행결과

 

 


+ typescript는 아니지만 한가지 팁

<argument 에서 default 값 설정 방법 (ES6 Javascript 구문임)>


원한다면 default 값을 argument에서 설정할 수 있다.

방법은 아래와 같다.

<Circle.tsx>
interface에서 text?: string;

하여 optional prop으로 만들어 준다음

밑에 Circle에서 argument로 text를 전달해주면서

text = "text가 없으면 표시될 문구를 작성" 해준다.

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


function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
  return (
    <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
      {text}
    </Container>
  );
}

export default Circle;


전체코드
<Cirlcle.tsx>

import styled from "styled-components";
// interface
interface ContainerProps {
  bgColor: string;
  borderColor: string;
}

interface CircleProps {
  bgColor: string;
  borderColor?: string;
  text?: string; // 1. text를 optional prop으로 작성해줌
}

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

// Circle Props
// 2. text를 argument로 받아주고 = "... " 를 작성하여 default text를 설정해줌
function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
  return (
    <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
      {text}
    </Container>
  );
}

export default Circle;



<App.tsx>

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

function App() {
  return (
    <div>
      <Circle bgColor="teal" borderColor="black" />
      <Circle bgColor="red" />
    </div>
  );
}

export default App;

 

 

실행결과

 

text를 작성해주지 않았기 때문에 default 값인

"default text" 가 출력되어 나옴.

 

 

반면, 한군데에 text를 작성해준다면

 

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

function App() {
  return (
    <div>
      <Circle bgColor="teal" borderColor="black" />
      <Circle bgColor="red" text="안녕" />
    </div>
  );
}

export default App;

 

 

실행결과

 

적어준 text 가 잘 반영되어

"안녕" 이 출력됨을 볼 수 있다.

 

 

 

Comments