Search code examples
javascriptreactjstypescriptdependency-injectiontypeof

How to assign classes to properties of "new () =>" type


There is a hierarchy

class Thing { }

class BarView<Type> extends React.Component<{ obj: Type }, {}> { }

class FlossView extends BarView<Thing> {  }

class Foo<Type> {
    renderer?: new () => BarView<Type>

    constructor(view?: new () => BarView<Type>) {
         this.renderer = view
    }
}

Why can I call the constructor of Foo with class name signature and not have any error like this

let foo = new Foo<Thing>(FlossView)

... while the following code produces an error?

let foo = new Foo<Thing>()
foo.renderer = FlossView
/* [ts]
Type 'typeof FlossView' is not assignable to type 'BarView<Thing> | undefined'.
Type 'typeof FlossView' is not assignable to type 'BarView<Thing>'.*/

How do I get the not typeof FlossView version of the class, but just FlossView?


Solution

  • Case closed. The signature is invalid, the most-base class React.Component has never ever had a constructor of type new () => React.Component.

    Figures, there is only a constructor with one parameter, props. And thus the type declaration of renderer property is invalid. It should be

    renderer?: new (props) => BarView<Type>