Is it possible to infer TYPES of props, based on component passed into a higher order component?

Viewed 19

For example I have a simple component like this:

interface HomeProps {
  date: number;
  greeting?: string;
}

function Home(props: HomeProps) {
  const { date, greeting } = props;
  return (
    <div>
      date: {date}, greeting: {greeting}
    </div>
  );
}

I have a higher order component like this:

function GreetingHOC<TOriginalProps>(
  Component: React.ComponentType<TOriginalProps>,
  props: TOriginalProps
) {

  const injectedProp = 'hello';

  return <Component greeting={injectedProp} {...props} />
}

With usage such as this:

const compProps = {
  date: +new Date(),
};

GreetingHOC<HomeProps>(Home, compProps);

As you can see I have to specify the types of compProps by using <HomeProps> notation in the in the GreetingHOC() call. Is there a way to type something, so that GreetingHOC checks the actual component being passed in for the required props, something like this:

export function GreetingHOC(
  Component: React.Component,
  props: typeof Component.props <-----
) {
}
0 Answers
Related