본문 바로가기
Frontend/TypeScript

[ 타입스크립트(TypeScript) ] PropsWithChildren으로 children 짧게 작성하기

by YWTechIT 2022. 9. 23.
728x90

📍 PropsWithChildren으로 children 짧게 작성하기

React에서 Component를 작성하다 보면 propschildren을 선언하는 경우가 종종 있다. 그런데, 매번 children과 해당 타입을 명시해주는 것은 번거롭지 않은가? 그래서 children의 타입을 따로 명시해주지 않아도 되는 react에서 지원하는 PropsWithChildren문법이 있다.

 

PropsWithChildrenReact.PropsWithChildren로 사용하거나 혹은 import { PropsWithChildren } from 'react'로 사용 할 수 있고 타입은 다음과 같다. type PropsWithChildren<P> = P & { children?: ReactNode | undefined }

 

코드를 살펴보면 childrenoptional하게 사용할 수 있고, 타입은 ReactNode이라는 점이다. 컴포넌트를 작성할 때 children의 타입을 ReactNode으로 사용했는데, 이를 생략할 수 있다니 상당한 문법이다.. 그럼 사용 예시를 살펴보자. AS-IS를 살펴보면 propschildren과 타입이 명시되어있는 것을 볼 수 있고 TO-BE에는 propschildren이 없는 것을 볼 수 있다. children 코드가 짧기 때문에 많이 줄었다고 보기 힘들지만 수고로움을 덜어준 것으로 만족한다.

728x90
// node_modules/@types/react/index.d.ts
type PropsWithChildren<P> = P & { children?: ReactNode | undefined };

// AS-IS
function Component1({ children, title }: { children?: ReactNode, title: string}){
  return(
     <div>
        <div className="title">{title}</div>
        {children}
     </div>
  )
}

// TO-BE
function Component2({ children, title }): PropsWithChildren<{ title: string }> {
  return(
     <div>
        <div className="title">{title}</div>
        {children}
     </div>
  )
}

반응형

댓글