typescript React Project

jangdu·2022년 10월 28일
0

typescript

목록 보기
6/16

project생성

yarn create react-app my-app --template typescript

기존 리엑트앱에 적용하려면

yarn add typescript @types/node @types/react @types/react-dom @types/jest

Component

import React from "react";

// component의 type선언시 interface를 사용해도된다
type GreetingsProps = {
    name: string;
};

const Greetings: React.FC<GreetingsProps> = ({ name }) => (
    <div>Hello, {name}</div>
);

export default Greetings;

React.FC를 사용하면 props의 타입을 generics로 넣어 사용한다.

그러면 props에 기본적으로 children이 들어있고, component의 defaultProps, propTypes, contextTypes를 설정할 때 자동완성이 가능하다.

그러나 children이 옵셔널 형태로 들어있어 컴포넌트의 props 타입이 비명화하다. GreetingsProps type을 통해서 children이 있다 없다를 명시해야만하는 단점이있다.

profile
대충적음 전부 나만 볼래

0개의 댓글