Skip to content

Unexpected props type for React component with constructor #25581

Closed
@OliverJAsh

Description

@OliverJAsh

TypeScript Version: 2.9.2

Search Terms: react component props type constructor implicit any hoc

Code

type RouteComponentProps = {
    history: {};
};

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

declare function withRouter<P extends RouteComponentProps>(
    component: React.ComponentType<P>,
): React.ComponentClass<Omit<P, keyof RouteComponentProps>>;

type FooProps = { foo: string } & RouteComponentProps;
class Foo extends React.Component<FooProps> {
    constructor(props) {
        super(props);
    }
}

// Expect error due to missing props, got one :-)
const a = <Foo />;
// Expect error due to missing props, got one :-)
const b = <Foo foo="1" />;

// However, after using a (correctly defined) HOC, the props type seems to go completely

const Foo2 = withRouter(Foo);

// Expect error due to missing props, but got none :-(
const c = <Foo2 />;

… unless we comment out the constructor, or annotate the props param:

class Foo extends React.Component<FooProps> {}

const Foo2 = withRouter(Foo);

// Expect error due to missing props, got one :-)
const c = <Foo2 />;
class Foo extends React.Component<FooProps> {
    constructor(props: Props) {
        super(props);
    }
}

const Foo2 = withRouter(Foo);

// Expect error due to missing props, got one :-)
const c = <Foo2 />;

Why does the presence of the constructor change the props type only after the component is ran through the HOC?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions