'How can I type a React component that renders a generic component?

I'm trying to build a component that can wrap a form control and provide some of its props. The issue is that the remainder of the props passed to this wrapper component need to be passed through to the wrapped control. I've been trying to type this in Typescript, but it's just not happening. Here's a simplified example of the issue:

import { ComponentProps, ElementType } from "react";

function Example(props: { a: string; b: string }) {
  return null;
}

function Problem<As extends ElementType>({
  as: Component,
  ...props
}: { as: As } & Omit<ComponentProps<As>, "a">) {
  return <Component a="blabla" {...props} />;
}

function Test() {
  return <Problem as={Example} b="asdf" />;
}

This code results in a Typescript error in the Problem component...

I've tried a million different ways and I always get an error somewhere. I'll also need to have a default value for that as prop, but that's a challenge for another day. Any help would be greatly appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source