Apparently, using React.ComponentProps is the correct way to extract the component
property types, however, i can't make it work in a generic function:
Sample component:
interface OwnProps {
value: string;
}
const TestComponent: SFC<OwnProps> = (props) => {
const { } = props;
return (
<div />
);
};
Generic function:
function myFunction<T extends React.ComponentType<any>>
(Component: React.ReactType, props: React.ComponentProps<T>) {
// implementation
}
Function Usage:
myFunction(TestComponent, {
value: 1 // not detecting invalid value
});
As you can see the value is assigned with a numeric value but the compiler is not detecting the error.
one way to do this is to use the function as follow:
myFunction<typeof TestComponent>(TestComponent, {
value: 1
});
it works, but i am curious how it can be done without using typeof.
function myFunction<T extends React.ComponentType<any>>
(Component: React.ReactType, props: React.ComponentProps<T>) {
// implementation
}
In this definition, Component can be any React.ReactType. There's no mention of T, so this is not going to enforce any relationship between the component and the props.
Instead, i believe you want this:
function myFunction<T extends React.ComponentType<any>>
(Component: T, props: React.ComponentProps<T> {
// implementation
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With