Type annotation for React Higher Order Component using TypeScript

后端 未结 2 721
一生所求
一生所求 2021-01-02 17:52

I am writing a Higher Order Component for my React project using Typescript which is basically a function accepts a React component as an argument and return a new component

相关标签:
2条回答
  • 2021-01-02 18:11

    Type annotation for React Higher Order Component using TypeScript

    The return type typeof React.Component is truthful, but not very helpful for users of the wrapped component. It discards information about what props the component accepts.

    The React typings provide a handy type for this purpose, React.ComponentClass. It’s the type of a class, rather than the type of the component created from that class:

    React.ComponentClass<Props>
    

    (Note that the state type isn’t mentioned as it’s an internal detail).

    In your case:

    export default function wrapperFunc <Props, State, CompState> (
        WrappedComponent: typeof React.Component,
    ): React.ComponentClass<Props & State> {
        return class extends React.Component<Props & State, CompState> {
            public render() {
                return <WrappedComponent {...this.props} {...this.state} />;
            }
        };
    }
    

    However, you’re doing the same thing with the WrappedComponent parameter. Based on how you’re using it inside render, I’m guessing that it should also be declared:

    WrappedComponent: React.ComponentClass<Props & State>,
    

    But this is wild guess as I assume this is not the complete function (CompState isn’t used, and Props & State may as well be a single type parameter as it always appears in that combination).

    0 讨论(0)
  • 2021-01-02 18:27

    A more appropriate type for the input parameter would be React.ComponentType, since it handles stateless components too.

    type ComponentType<P = {}> = ComponentClass<P> | StatelessComponent<P>
    

    Following is an example clarifying its usage.

    import * as React from 'react';
    
    export default function <P = {}>(
      WrappedComponent: React.ComponentType<P>
    ): React.ComponentClass<P> {
      return class extends React.Component<P> {
        render() {
          return <WrappedComponent {...this.props} />;
        }
      };
    }  
    
    0 讨论(0)
提交回复
热议问题