Skip to content

React: Type inference with ComponentClass results in any #14176

Closed

Description

@frenic

Using type argument inference with React.ComponentClass<P> in @types/[email protected] to @types/[email protected] results in P being any.

class Foo extends React.Component<{foo: string}, void> {
  render() {
    return <div />
  }
}

function func<P>(base: React.ComponentClass<P>): React.ComponentClass<P> {
  return base;
}

// const Bar: React.ComponentClass<any>
const Bar = func(Foo);

With @types/[email protected] results in:

// const Bar: React.ComponentClass<{ foo: string }>
const Bar = func(Foo);

Is this a bug or is there another way to infer props now?

Activity

  1. changed the title [-]React: Generic in `ComponentClass` results in `any`[/-] [+]React: Type inference with `ComponentClass` results in `any`[/+] on Jan 22, 2017
  2. jwbay commented on Jan 23, 2017

    @jwbay
    Contributor

    Root cause seems to be way back in #11612. When I remove that constructor from the typings locally, inference sites light up.

  3. added a commit that references this issue on Jan 24, 2017
    1001a8e
  4. added a commit that references this issue on Jan 25, 2017
    6a8f836
  5. samijaber commented on Jun 7, 2018

    @samijaber
    Contributor

    This issue should be reopened. This bugs currently exists with the latest version of @types/react, and can be reproduced by instantiating the component's constructor. Here's an updated example:

    type Props = { foo: string }
    class Foo extends Component<Props> {
      constructor(props) {
        super(props)
      }
    
      render() {
        return <div />
      }
    }
    
    function func<P>(base: React.ComponentClass<P>): React.ComponentClass<P> {
      return base;
    }
    
    // const Bar: React.ComponentClass<any>
    const Bar = func(Foo);

    One way to fix this is to make sure to annotate the constructor's argument, i.e.

    class Foo extends Component<Props> {
      constructor(props: Props) {
        super(props)
      }
    
      render() {
        return <div />
      }
    }

    This makes ComponentClass's type inference work correctly.

  6. jardakotesovec commented on Jun 12, 2018

    @jardakotesovec

    @samijaber Hi, just noticed the same problem. I think it will be necessary to create new issue.. closed issues often not get much attention.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions