TS interface

최정환·2021년 12월 2일
0

TS

목록 보기
2/2

Props Typing(Props type required)

🔧 interface에 선언을 해놓는다면 required상태가 된다.

interface PlayerShape{
 name:string;
 age:string;
}

const sayHello = (playerObj:PlayerShape)=>
`Hello ${playerObj.name} you are ${playerObj.age} years old`

sayHello({name:"jung",age:"20"}) // ok
sayHello({name:"jung",age:20})	// age에서 오류

Optional Props (Props type optional required)

🔧 선택적으로 interface에 선언하고 싶다면 "?"를 사용한다.

// Containrt가 가져야 하는 interface bgColor={bgColor}일때 왼쪽 것
interface ContainerProps {
  bgColor: string;
  borderColor: string;
}

// TS에게 Container가 interface ContainerProps에 있는 props들을 받을 거라 말함
const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  border-radius: 100px;
  border: 1px solid ${(props) => props.borderColor};
`;

// ts에서 변수 타입 설정, obect shape를 ts에게 설명
interface CircleProps {
  bgColor: string;
  borderColor?: string;
  text?:string
}

// null병합연산자를 사용해 borderColor가 undefined면 bgColor로 대체한다.
function Circle({ bgColor, borderColor,text="default value" }: CircleProps) {
  return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor} >
    {text}
    </Container>;
}
function App() {
  return (
    <div>
      <Circle bgColor="teal" />
      <Circle bgColor="tomato" borderColor="blue" />
    </div>
  );
}


null병합연산자
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

0개의 댓글