import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import CourseGoal from "./components/CourseGoal";
import "./App.css";
function App() {
const [count, setCount] = useState(0);
return (
<main>
<CourseGoal
title="Learn React + TS"
description="Learn it from the froun up"
/>
</main>
);
}
export default App;
1. interface에서 children에 ReactNode를 정의해주는 방식
ReactNode는 React에 내장되어있는 특별한 type.
import { type ReactNode } from "react";
interface CourseGoalProps {
title: string;
description: ReactNode;
}
const CourseGoal = ({ title, description }: CourseGoalProps) => {
return (
<div>
<h2>{title}</h2>
<p>{description}</p>
<button>Delete</button>
</div>
);
};
export default CourseGoal;
2. PropsWithChildren을 사용하는 방식
import { PropsWithChildren } from "react";
type CourseGoalProps = PropsWithChildren<{
title: string;
description: string;
}>;
const CourseGoal = ({ title, description }: CourseGoalProps) => {
return (
<div>
<h2>{title}</h2>
<p>{description}</p>
<button>Delete</button>
</div>
);
};
export default CourseGoal;
3. 함수형 컴포넌트에서 FC
import { FC, PropsWithChildren } from "react";
type CourseGoalProps = PropsWithChildren<{
title: string;
description: string;
}>;
const CourseGoal: FC<CourseGoalProps> = ({ title, description }) => {
return (
<div>
<h2>{title}</h2>
<p>{description}</p>
<button>Delete</button>
</div>
);
};
export default CourseGoal;
참고
import 시 type이라는 데코레이터를 붙여주면 빌드시 제거 가능
import { type PropsWithChildren } from "react";
'공부기록 > Typescript' 카테고리의 다른 글
# 50 타입의 다양한 활용 유니언 타입, ComponentPropsWithoutRef, Button컴포넌트 (0) | 2023.11.15 |
---|---|
useState / Formevent /setState / useRef 타입지정 (0) | 2023.11.15 |
화살표 함수에 제네릭 사용하기 (0) | 2023.11.14 |
리액트에서 타입스크립트로 마이그레이션 하기 III - 확장자 변경시 에러 수정 목록 redux, props, component type 수정,,, (0) | 2023.11.13 |
리액트에서 타입스크립트로 마이그레이션 하기 II -절대경로설정 with craco (0) | 2023.11.13 |