Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React.ComponentProps in a generic function

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.

like image 336
cyrus-d Avatar asked Aug 16 '26 07:08

cyrus-d


1 Answers

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
}
like image 75
Nicholas Tower Avatar answered Aug 18 '26 23:08

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!