[React] 리액트 타입 연결하기
리액트 타입 연결 방법과 사용법 (React + TypeScript)
리액트 프로젝트에 타입스크립트를 적용하고, 컴포넌트에 타입을 연결하는 방법을 단계별로 정리했습니다.
처음 리액트와 타입스크립트를 접하는 분도 쉽게 따라할 수 있도록 설명합니다.
타입스크립트와 리액트를 함께 사용하면 타입 안정성, 가독성, 유지보수성이 모두 향상됩니다.
1. 타입스크립트 적용 (설치 및 환경설정)
새 프로젝트 생성 시
npx create-react-app my-app --template typescript
yarn create react-app my-app --template typescript
위 명령어로 타입스크립트가 적용된 리액트 프로젝트를 바로 시작할 수 있습니다.
기존 프로젝트에 타입스크립트 추가
- 타입스크립트 및 타입 패키지 설치
npm install --save typescript @types/node @types/react @types/react-domyarn add typescript @types/node @types/react @types/react-dom - tsconfig.json 생성 및 설정
주요 옵션 예시:{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"] } - 파일 확장자 변경
.js→.ts,.jsx→.tsx로 변경하세요.
2. 리액트 컴포넌트에 타입 연결 (Props 타입 선언)
컴포넌트에 타입을 연결하는 방법 3가지 입니다.
1) interface 또는 type을 사용한 Props 타입 선언
import React from 'react';
interface CircleProps {
bgColor: string;
borderColor?: string;
text?: string;
}
const Circle: React.FC<CircleProps> = ({ bgColor, borderColor, text }) => (
<div style={{
backgroundColor: bgColor,
border: borderColor ? `2px solid ${borderColor}` : undefined,
borderRadius: '50%',
width: 100,
height: 100,
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}>
{text}
</div>
);
export default Circle;
2) React.FC 제네릭 사용
type AppProps = { title: string };
const App: React.FC<AppProps> = ({ title }) => {
return <h1>{title}</h1>;
};
3) 인라인 타입 선언
const App = ({ title }: { title: string }) => {
return <h1>{title}</h1>;
};
3. 예시 코드
App.tsx
import React from 'react';
import Circle from './Circle';
function App() {
return (
<div>
<Circle bgColor="red" borderColor="black" />
<Circle bgColor="blue" text="text" />
</div>
);
}
export default App;
Circle.tsx
interface CircleProps {
bgColor: string;
borderColor?: string;
text?: string;
}
const Circle: React.FC<CircleProps> = ({ bgColor, borderColor, text }) => (
<div style={{
backgroundColor: bgColor,
border: borderColor ? `2px solid ${borderColor}` : undefined,
borderRadius: '50%',
width: 100,
height: 100,
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}>
{text}
</div>
);
export default Circle;
타입스크립트를 적용하면 props의 타입을 확인하여 잘못된 타입 전달 시 컴파일 단계에서 에러를 확인할 수 있습니다.
정리
- 타입스크립트 적용: 패키지 설치 → tsconfig 설정 → 파일 확장자 변경
- 컴포넌트 타입 연결: interface/type 선언 후 React.FC<Props> 또는 인라인 타입 활용
- 실무에서는 interface를 활용한 props 타입 선언이 가장 많이 사용됨
- styled-components, CSS 모듈 등과 함께 사용할 때는 추가 타입 선언이 필요할 수 있습니다.
- 예: CSS 모듈 사용 시 global.d.ts에 declare module "*.module.css"; 추가
- 타입스크립트와 리액트의 조합은 props, state, ref, 이벤트 등 다양한 부분에 타입을 적용할 수 있습니다.
- 공식 문서나 cheatsheet를 참고하면 실무에서 자주 쓰는 패턴을 빠르게 익힐 수 있습니다.
728x90
'React' 카테고리의 다른 글
| [React] LocalStorage(로컬스토리지) - 저장, 불러오기, 삭제 (1) | 2025.05.29 |
|---|---|
| [React] Props(프롭스)란? (0) | 2025.05.28 |
| [React] UseState란? (0) | 2025.05.27 |
| [React] UseMemo란? (0) | 2025.05.22 |
| [React] React Router 설정방법 (2) | 2025.05.21 |