根据配置动态推断 prop 类型

问题描述 投票:0回答:1

是否可以根据同一 prop 中提供的组件类型动态推断正确的 prop 类型?

目前我的组件可以根据提供的组件类型正确推断预期的道具。

export interface IFieldTypeProps<TComponent extends React.ComponentType<any>> {
  type: TComponent;
  props: React.ComponentProps<TComponent>;
}

export function Field<TComponent extends React.ComponentType<any>>({
  type: Component,
  props,
}: IFieldTypeProps<TComponent>) {
  return <Component {...props} />;
}

<Field type={TextField} props={{ required: true, label: "First Name" }} />; // expected prop type inferred based on type prop

我想使用严格的配置而不是 JSX 来做类似的事情。这可能吗?

示例:

const fields = [
  {
    type: TextField,
    props: { required: true, label: "First Name" }, // Typecheck not working should infer props based on type above
  }, 
];

const Form = () => {
  return (
    fields.map((field) => {
      <field.type {...field.props}/>
    })
  )
}
reactjs typescript react-props
1个回答
1
投票

这是一种利用函数参数推断来保持接近纯定义方式但添加强类型验证的方法:

type Field<Props> = {
    Component: React.ComponentType<Props> | React.FC<Props>,
    props: Props,
};

const createField = <Props, >(
    Component: React.ComponentType<Props> | React.FC<Props>,
    props: Props,
): Field<Props> => ({
        Component,
        props,
    });

const fields = [
    createField(
        TextField,
        { required: true, label: "First Name" },
    ),
    createField(
        TextField,
        { required: true, label: "Last Name" },
    ),
];

export const Form = ({
}) => (
    fields.map(({ Component, props }) => <Component {...props}/>)
);
© www.soinside.com 2019 - 2024. All rights reserved.