TypeScript(react)

EunRyeong Park·2022년 10월 31일
0

typescript

목록 보기
11/11
  • 타입스크립트 마이그레이션
  1. 타입스크립트 마이그레이션을 위한 라이브러리 설치
  2. tsconfig.json 설정
  3. 사용하는 라이브러리들 중 @types 패키지 추가
  4. webpack 설정 변경
  5. .jsx -> .tsx로 확장자 변환

✔️라이브러리 설치

npm i -D typescript esbuild-loader @types/react @types/react-dom
yarn add -D typescript esbuild-loader @types/react @types/react-dom
//efinitelyTyped 오픈소스에 등록된 타입 선언 파일 설치
npm i -D @types/<library name>
//webpack.config.js
module.exports = {
    //entry:앱을 시작할 파일
	entry: "./src/app.tsx",
  //output: 웹팩 번들링 결과에 대한 옵션. 기본경로는 dist
	output: {
		filename: "./bundle.js",
		},
  //resolve: 번들링할 확장자 설정
	resolve: {
		extensions: [".js", ".jsx", ".ts", ".tsx"],
		},
  //module: 번들링할 때 플러그인 설정 가능
	module: {
		rules: [
			{
            test: /\.(t|j)sx?$/,
            // esbuild-loader: 타입스크립트 변환을 위한 로더
            loader: "esbuild-loader",
            options: {
            loader: "tsx", // Or 'ts' if you don't need tsx
            target: "es2015",
			},
		},
		{
			test: /\.css$/,
          //css-loader: .css 확장자의 css파일을 읽기 위한로더
          //style-loader: style태그를 삽입해 dom에 css추가
			use: ["style-loader", "css-loader"],
		},
	],
	},
  //externals: 번들링 결과에서 제외할 라이브러리들
externals: {
	react: "React",
	"react-dom": "ReactDOM",
	},
};
  

✔️타입스크립트 프로젝트 시작하기

npx create-react-app <프로젝트 이름> -template typescript

Props 타입 적용

export const Button = (props: React.PropsWithChildren<ButtonProps>) => {
return <button {...props} }>{props.children}</button>;
}
  • {…props}: 스프레드 연산자로 props를 button의 props에 모두 전달
  • React.PropsWithChildren: 제네릭에 전달한 props와 props.children을 인터섹션
  • props.children: react에서 기본적으로 전달해주는 children props. 자식 노드들이 전달됨
export const Button: React.FC<ButtonProps> = (props) => {
	return <button style={props.buttonStyles}>{props.children}</button>;
};
type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
	(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
}
//React.FC 타입을 사용하면 내부적으로 PropsWithChildren을 사용하여
//제네릭의 Props 타입과children 타입을 인터섹션.props에
//React.PropsWithChildren을 선언하는 것과 같은 효과

Hook에 타입 적용

  • useState타입
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];
                           
                                     
//초기값으로 state 타입을 결정                                   
const [name, setName] = useState(null)

//초기값이 없다면 undefined로 설정
const [name, setName] = useState()

💥React에서의 타입스크립트

  1. generic props
  • props를 제네릭 인터페이스로 선언
  • 함수 시그니처에서 괄호 앞에 타입 파라미터 T 선언
  • interface가 객체의 형태기 때문에 {} 객체 리터럴을 extends하는 제약 조건 추가
  • 사용 시에 props만 전달하면 타입이 알아서 추론
  1. template literal type

  2. 다른 컴포넌트의 props 추출

  • 기존 컴포넌트를 확장할 때 컴포넌트의 props를 그대로 사용한다면 똑같은 props 인터페이스를 만들지 않고 React.ComponentProps<typeof컴포넌트>를 사용

0개의 댓글