[React] 타입스크립트 기본 문법

soyeon·2022년 3월 1일
0

TIL

목록 보기
11/32
post-thumbnail

💙타입스크립트

  • 자바스크립트 ESNext(15~)에 타입 기능을 끼얹음
  • strongly-typed: 코드 실행 전 데이터의 타입을 알 수 있음
  • 오류들을 친절하게 알려줘서 규모가 있는 프로젝트에서 잘 쓰인다.
    예시)
const plus = (a:number, b:number)=> a+b;
//a와 b의 타입을 숫자로 지정
plus("a",1)
//"a"에 빨간 밑줄이 팍팍 그어지며 틀린 부분을 지적해준다.

💙설치해봅시다

npm i --save typescript @types/node @types/react @types/react-dom @types/jest

스타일드 컴포넌트를 쓸 때

npm i --save-dev @types/styled-components

변수에 타입 적용하기 (타입 주석)

  • 자바스크립트 변수 선언문을 확장해서 타입을 명시합니다.

    let 변수이름 : 타입
    const 변수이름 : 타입

let n: number = 1
let b: boolean = true
//interface도 적용할 수 있다.
const theme: DefaultTheme = {...};

💙props의 타입 지정하기(interface)

  • 컴포넌트에 bgColor props 지정
    App.tsx
return
	<div>
  		<Circle bgColor="red" />
  • interface는 object 형태로 작성합니다.
  • 오브젝트 이름 마음대로 지어도 됨
  • interface를 만들면 스타일드 컴포넌트와 함수형 컴포넌트 둘 다 적용을 시켜줘야함
    Circle.tsx
	interface CircleProps {
      bgColor:string
      //문자열 타입으로 지정
    }

	const Container = styled.div<CircleProps>`

const Container = styled.div<CircleProps>`
    //스타일드 컴포넌트에 interface 적용
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: ${(props) => props.bgColor};
`;

	function Circle({bgColor}:circleProps) {
      //props에 interface 적용
    	return <Container bgColor={bgcolor} />
    }

💥그러나 bgColor:string라고 쓰면 isRequired 상태가 됨
=> Circle 컴포넌트들이 모두 bgColor Props를 갖고 있어야하는 상황

interface의 props의 required 상태를 해제하기(선택옵션)

interface CircleProps {
  bgColor?: string;
}
  //props 뒤에 ?를 붙여주면 됨
  • bgColor?:stringcolor:string | undefined의 결과값은 같다.

prop의 기본값 정하기(해당 prop 값이 undefined일 때)

<Container borderColor = {borderColor ?? "red"} />

💙state의 타입 지정하기

const [value, setValue] = useSatate<number|string>(1);
//number, string 타입을 지정

📎참고

React JS 마스터 클래스 - 노마드코더
Do it! 타입스크립트 프로그래밍 - 전예홍, 이지스퍼블리싱
더 추가될 수도 있음

profile
공부중

0개의 댓글