React TypeScript – Props not recognized when component is wrapped in some high order components

It is so annoying when you developed your component nicely but when you need to wrap it with some high order components from some cool plugins, props suddenly doesn’t get recognized by the TypeScript compiler. Without knowing the proper way of dealing it, I ended up doing some weird workaround.

Component Structure

Here is my example child component wrapped inside a Form hoc from Ant Design (note that form props is part of Ant Design’s hoc):

import React from 'react';
import { Form } from "antd";

type Props = {
  children?: any,
  form: any,
  onCreate: any,
};

type State = {};

class FooBar extends React.Component<Props, State> {
  state = {};

  render() {
    return (
      <></>
    );
  }
}

export default Form.create()(FooBar);

And here is the parent component:

import React from 'react';
import FooBar from "./foo";

type Props = {
  children?: any
};

type State = {};

export class BarBar extends React.Component<Props, State> {
  state = {};

  render() {
    return (
      <div>
        <FooBar onCreate={null} />
      </div>
    );
  }
}

The compiler throws this error:

Property 'onCreate' does not exist on type 'IntrinsicAttributes &amp; IntrinsicClassAttributes<Component<Pick<FormComponentProps<any>, "wrappedComponentRef">, any, any>> &amp; Readonly<Pick<FormComponentProps<any>, "wrappedComponentRef
">> &amp; Readonly<...>'

Solution

While looking at the definitions of these high order components, they provide a way to specify the type using the brackets syntax like this: Foo.bar<TypeHere>(params). This is what I needed to do to make it work with probably most of those high order components.

Since we already have the Props definition, I just specify it in Form.create.

export default Form.create<Props>()(FooBar);

After this change, WebStorm and compiler now happily compiles the code.

That’s it!

This entry was posted in React, TypeScript and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *