공부기록/Typescript
props.children 타입 정의 방법
Jenner
2023. 11. 15. 10:07
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";