gka
gka

Reputation: 509

defining props with TypeScript when using higher order component

I have a component that needs to get injected from both parent (with PropA) and from HOC (with PropB)

export interface PropsA extends PropsB {
    propA: string;
}

class SomeComponent extends React.PureComponent<PropsA> {
    render(){
        return (
            <div>
                {this.props.propA}
                {this.props.propB}
            </div>
        );
    }
}

export default withPropsB(SomeComponent);


export interface PropsB {
    propB: string;
}

This is how we inject it with HOC:

export const withPropsB = (Component: any) => {
    class EnhancedWithProsB extends React.Component<PropsB> {
        render(){
            return <Component {...this.props}/>;
        }
    }

    const mapStateToProps = (state: any) => ({
        propB: "propB"
    });

    return connect(mapStateToProps)(EnhancedWithProsB);
};

Client use it this way:

class Wrapper extends React.Component {
    render(){
        return <SomeComponent propA="propA" />;
    }
}

I got error saying that "Property 'propA' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes, ComponentState>> & ...'."

What type should withPropsB method return to make this error dissapear?

Upvotes: 1

Views: 479

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

You need to derive EnhancedWithProsB from React.Component with the same props as the component passed (in your case PropsA). A generic way to that would be:

export const withPropsB = <T extends PropsB>(Component: new(... p: any[])=>  React.PureComponent<T>) => {
    class EnhancedWithProsB extends React.Component<T> {
        render(){
            return <Component {...this.props}/>;
        }
    }

    const mapStateToProps = (state: any) => ({
        propB: "propB"
    });

    return connect(mapStateToProps)(EnhancedWithProsB);
};

Upvotes: 3

Related Questions