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
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-09 23:59:14 +0000
Seen: 10 times
Last updated: Jul 10 '23
How can one ensure that sub-classes have uniform method parameters in TypeScript?
Can a TypeScript definition for icon names be provided in MaterialCommunityIcons for React Native?
How can TypeScript be used to save a file in an Excel add-in?
What is the Angular Type script NG Zorro event for radio buttons?
What is the process for implementing a Many to Many relationship using NestJs Sequlize and Mysql2?
What is the method for defining a Fixed length Array in TypeScript?
What difficulties are encountered in the installation of react-router-dom using typescript?