NavBar가 외부 라이브러리에서 가져온 컴포넌트라고 가정해 보겠습니다.

// Imagine NavBar is an external library!

export const NavBar = (props: {
  title: string;
  links: string[];
  children: React.ReactNode;
}) => {
  return <div>Some content</div>;
};

어떤 이유에서인지 작성자는 props를 export하지 않았습니다. 테스트의 오류에서 볼 수 있듯이 재사용 가능한 타입으로 가져올 수 없습니다.

// Your app:

import { Equal, Expect } from "../helpers/type-utils";

type NavBarProps = unknown;

type test = Expect<
  Equal<
    NavBarProps,
    {
      title: string;
      links: string[];
      children: React.ReactNode;
    }
  >
>;

Challenge

여러분의 과제는 내비게이션 바의 props를 가져와 타입으로 끌어당기는 방법을 찾는 것입니다.

type NavBarProps = unknown

힌트: props를 잡는데 도움이 되는 재사용 가능한 타입헬퍼를 React에서 찾아보세요!

Use a Type Helper to Extract Component Props

이 솔루션은 실제로 이전에 사용했던 것을 사용합니다.

먼저 ComponentProps 를 React에서 import 해봅시다.

import { ComponentProps } from "react";

ComponentProps를 사용하는 방법은 두 가지가 있습니다. 실제 HTML DOM 엘리먼트를 전달거나 기존 컴포넌트를 전달할 수 있습니다.

typeof NavBar 를 전달하면 ComponentPropsNavBar 자체에서 모든 props를 추출합니다.

type NavBarProps = ComponentProps<typeof NavBar>;