'How to constrain generic to be a type that can be props of a react component?
I just finished fighting with the typescript compiler to create a component that takes another component as a prop- and then requires all that components props as props to pass to it. (The use case is for Gatsby <PrivateRoute> components).
I've managed to actually get it working, but the problem is I can't figure out why this works.
Here is a simplified example:
The wrapper component and defined props:
type WrapperProps<T> = { component: React.ComponentType<T> } & T;
const Wrapper = <T extends object>({
component: Component,
...rest
}: WrapperProps<T>) => {
return <Component {...(rest as T)} />;
};
and the intended use:
interface person {
name: string;
age: number;
}
const ShowPerson = ({ name, age }: person) => {
return (
<h1>
{name}, {age}
</h1>
);
};
const Display = () => {
return <Wrapper component={ShowPerson} name="T" age={12} />;
};
The part that I can't figure out why its working is in the generic constraint in the wrapper component. If I remove <T extends object>, I will get an error "conversion of type 'Omit<WrapperProps<T>,"component"> to type 'T' may be a mistake because neither type sufficiently overlaps with the other
Now, it makes sense that the generic needs to be constrained, but is there a better constraint than using <T extends object> ? Why does <T extends {}> not work? What would be an acceptable and better generic constraint that would work as the props of a React component? extends object does not feel like the correct solution to me.
Edit
This can also be functional by casting ...rest as unknown as T, but I'm still struggling to wrap my head around it:
const Wrapper = <T,>({
component: Component,
...rest
}: WrapperProps<T>) => {
return <Component {...(rest as unknown as T)} />;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
