[React Typescript] Extracting Props from Custom Components

发布时间 2023-05-22 14:19:42作者: Zhentiw
// Imagine NavBar is an external library!

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

// Your app:

import { Equal, Expect } from '../helpers/type-utils';
type PropsFrom<TComponent> = TComponent extends React.FC<infer Props>
  ? Props
  : TComponent extends React.Component<infer Props>
  ? Props
  : never;
type NavBarProps = PropsFrom<typeof NavBar>;

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

 

Or:

import type { ComponentProps } from 'react';

type NavBarProps = ComponentProps<typeof NavBar>;