Typescript: `typeof React.Component` stopped working

Created on 4 Oct 2017  ·  6Comments  ·  Source: microsoft/TypeScript



TypeScript Version: 2.5.3

Code

class MyComponent extends React.Component<{}, {}> {
  render () {
    return null
  }
}

function thisTakesAComponent (component: typeof React.Component) {

}

thisTakesAComponent(MyComponent)

Expected behavior:
Should compile fine.

Actual behavior:

Argument of type 'typeof MyComponent' is not assignable to parameter of type 'typeof Component'.
  Type 'MyComponent' is not assignable to type 'Component<P, S>'.
    Types of property 'setState' are incompatible.
      Type '{ <K extends never>(f: (prevState: {}, props: {}) => Pick<{}, K>, callback?: (() => any) | undefi...' is not assignable to type '{ <K extends keyof S>(f: (prevState: S, props: P) => Pick<S, K>, callback?: (() => any) | undefin...'.
        Types of parameters 'f' and 'f' are incompatible.
          Types of parameters 'prevState' and 'prevState' are incompatible.
            Type '{}' is not assignable to type 'S'.
Working as Intended

Most helpful comment

why not:

 function thisTakesAComponent <P>(component: React.SFC<P> | React.ComponentClass<P>) {
 }

All 6 comments

MyComponent is not of type typeof React.Component, it's of type typeof MyComponent. This probably used to work before #16368, since we ignored the generic type arguments before, which made them indistinguishable.
If you want a type of subclasses of React.Component, you could use something like { new(): React.Component<any, any> } -- of course this depends on how you plan to use the variable.

And what about for stateless functions? IE I don't want "a type of subclasses of React.Component", I want "something that will be rendered correctly with React.createElement".

I guess that depends on what react needs available on such a type -- I'm not familiar with the library so I couldn't tell you.

why not:

 function thisTakesAComponent <P>(component: React.SFC<P> | React.ComponentClass<P>) {
 }

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Not sure if this was applicable when originally asked, but now you can do this:

    function thisTakesAComponent(component: ReactType) {
    }
Was this page helpful?
0 / 5 - 0 ratings