You can define a generic Props interface for the wrapper component and then use the Pick utility type to select only the props that match a certain interface. Here's an example:
import React, { ComponentType } from "react";
// define a generic Props interface for the wrapper component
interface WrapperProps<P> {
component: ComponentType<P>;
props: Pick<P, "propA" | "propB">; // use Pick to select only certain props
}
// define a component that takes a propA and a propB
interface MyComponentProps {
propA: string;
propB: number;
}
// create a component that will be wrapped
const MyComponent = ({ propA, propB }: MyComponentProps) => (
<div>
<p>{propA}</p>
<p>{propB}</p>
</div>
);
// create a wrapper component that passes propA and propB to the wrapped component
const Wrapper = <P extends {}>({ component: Component, props }: WrapperProps<P>) => (
<Component {...props as P} />
);
// use the wrapper component to wrap MyComponent and pass only propA and propB
const App = () => (
<Wrapper component={MyComponent} props={{ propA: "hello", propB: 123 }} />
);
In this example, we define a WrapperProps
interface with two generic type parameters: P
for the component's props, and W
for any additional wrapper props (in this case, we only have component
and props
). We use the Pick
utility type to select only the props that match the MyComponentProps
interface, and then pass that to props
in the Wrapper
component. Finally, we use as P
to assert that the props
variable matches the component's expected props, and use the spread operator to pass those props to the Component
.
Asked: 2023-07-09 23:59:14 +0000
Seen: 11 times
Last updated: Jul 10 '23