React TypeScript generics: How to resolve " not assignable to type 'IntrinsicAttributes & LibraryManagedAttributes"?

229 Views Asked by At

I'm creating a higher order component (HOC) that will provide some property values to a component, so that this component can be used by a parent component, without supplying those values.

What I want to achieve

I want to be able to wrap this component:

<MyInnerComponent someProp="some value" suppliedProp="supplied value" />

in the HOC:

const WrappedComponent = wrap(MyInnerComponent, () => ({suppliedProp: "supplied value"}))

and then use it from a parent component like this:

<WrappedComponent someProp="some value" />

so that it renders like this:

<div>someProp: some value, suppliedProp: supplied value</div>

I have implemented the HOC:

export function wrap<
  DataProps,
  InnerComponentType extends React.ComponentType<Props>,
  Props extends DataProps
>(
  InnerComponent: InnerComponentType,
  dataPropsProvider: (
    props: Omit<React.ComponentProps<InnerComponentType>, keyof DataProps>
  ) => DataProps
) {
  return (
    outerProps: Omit<React.ComponentProps<InnerComponentType>, keyof DataProps>
  ) => {
    const dataProps: DataProps = dataPropsProvider(outerProps);
    // This is the problem:
    return <InnerComponent {...outerProps} {...dataProps} />;
  };
}

The problem

Upon rendering the InnerComponent, there's a TypeScript error:

Type 'Omit<ComponentProps, keyof DataProps> & DataProps' is not assignable to type 'IntrinsicAttributes & LibraryManagedAttributes<InnerComponentType, Props>'

What I've tried

Adding the constraint IntrinsicAttributes & LibraryManagedAttributes<InnerComponentType, Props> to the DataProps parameter:

export function wrap<
  DataProps extends JSX.IntrinsicAttributes & JSX.LibraryManagedAttributes<InnerComponent, Props>,
  InnerComponentType extends React.ComponentType<Props>,
  Props extends DataProps
>(

... but this is a circular constraint.

I'm not sure I understand the requirement for extending JSX.IntrinsicAttributes and JSX.LibraryManagedAttributes.

How can I satisfy the requirement?

There's a Code Sandbox demo.

0

There are 0 best solutions below