从 React 组件中提取 props 类型

Extract props type from React component

我正在尝试了解如何(如果可能的话)从给定组件中提取道具类型。

const Component = (props: { color: string }) => <div {...props} />;

type ComponentProps = $ExtractArguments<typeof Component>[0] // pseudo-code

我在谷歌上找到了这个实用程序,但我不知道它是否有用...

type $Arguments<F> = $Call<<A: $ReadOnlyArray<mixed>>((...A) => mixed) => A, F>;

您正在寻找 React.ElementProps 或 React.ElementConfig。最后一个考虑到了defaultProps,所以在实践中更有用。

Docs

Try

import * as React from 'react';

const Component = (props: { color: string }) => <div {...props} />;

type Props = React.ElementConfig<typeof Component>;