타입명시하기

정중식·2023년 3월 20일
0

타입스크립트

목록 보기
2/2

interface

  • object shape(객체모양)을 타입스크립트에게 설명해주는 타입스크립트의 개념이다.

1

  • props 타입 명시하기

Ex)

import styled from 'styled-components';

const Container = styled.div``;

interface CircleProp {
  bgColor: string;
}

const Circle = ({ bgColor }: CircleProp) => {
  return <Container bgColor={bgColor} />;
};

export default Circle;

2

  • styled-components 타입 명시하기
import styled from 'styled-components';

const Container = styled.div<ContainerProps>``;

interface ContainerProps {
  bgColor: string;
}

interface CircleProp {
  bgColor: string;
}

const Circle = ({ bgColor }: CircleProp) => {
  return <Container bgColor={bgColor} />;
};

export default Circle;
  • 이런식으로 optional로 만들어줄 수 있다.
interface CircleProp {
  bgColor: string;
  borderColor?: string;
  // 혹은 이렇게도 작성가능하지만,
  // 너무 기니깐 optional로 작성해주자..
  // borderColor: string || undefined;
}

state

1

타입스크립트는 리액트의 state의 타입을 추측해서 그 타입과 일치하지않을 경우 알려준다.

Ex)

const [value,setValue]=useState(0);
setValue('hello');

2

대체로 우리는 useSate()에 디폴트 값을 주면, 그 값이 문자열이면 계속 문자열로 사용되고, 그 값이 넘버면 넘버로 사용되기에 크게 신경을 안쓰고 살아왔지만,

만약 useState엔 예를들어 번호 혹은 문자열이 들어올수도있게 해주고싶다고 명시해주고 싶을 경우 다음과 같이 해주면된다.

const [value, setValue] = useState<number | string>(0);

하지만 이걸 사용하는 일은 많지 않다고한다.
state를 만들면 보통 같은 타입으로 쭉- 가기 때문에..

profile
내 가치를 찾아서

0개의 댓글