0

Is it possible to dynamically infer the correct prop type based on component type provided in same prop?

Currently I have component which correctly infers the expected props based on the provided component type.

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

I want to do do something similar using strictly config and no JSX. Is this possible?

Example:

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}/>
    })
  )
}

1 Answer 1

1

Here is a way which take advantage of function parameters inference to stay as close a a pure definition way but adding strongly typed verification:

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}/>)
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.