How do I make a higher order React component with Typescript?

Viewed 180

I'm trying to make a higher order component with Typescript, but I'm getting a type mismatch. I completely stripped it down, so it should just wrap the component, but still getting the error:

import * as React from 'react';

export function createPage<Props extends {}, ComponentType extends React.ComponentType<Props>>(
  Component: ComponentType
) {
  return class WrappedComponent extends React.Component<Props> {
    render() {
      return <Component {...this.props}></Component>;
    }
  }
}

The error I'm getting is:

Type 'Readonly & Readonly<{ children?: ReactNode; }>' is not assignable to type 'IntrinsicAttributes & LibraryManagedAttributes<ComponentType, PropsWithChildren>'.

It looks like IntrinsicAttributes can match nothing, but LibraryManagedAttributes is absolutely inscrutable to me.

1 Answers

You only need to provide a generic argument for the Props

export function createPage<Props>(
  Component: React.ComponentType<Props>
) {
  return class WrappedComponent extends React.Component<Props> {
    render() {
      return <Component {...this.props}></Component>;
    }
  }
}

Playground

Related