0

I have a base class which extends React.Component and is extended by several child classes. Now I want to have the type of the Parent class as the type of a property, and all Child classes should be valid for the property. I had a try of this answer, but it doesn't work when Parent extends React.Component.

class Parent extends React.Component{}
class Child1 extends Parent {}
class Child2 extends Parent {}
type F = {
  cp: { new(): Parent }
}
let f: F = {
  cp: Child1 //type 'typeof Child' is not assignable to type 'new () => Parent'.
}

1 Answer 1

1

Your constructor signatures mandates that the type have an empty constructor, but the constructor inherited from React.Component has two parameters. This is why typeof Child is not assignable to new ()=> Parent. You need to specify the constructor takes these arguments:

class Parent extends React.Component { }
class Child1 extends Parent { }
type F = {
    cp: { new(props: any, context?: any): Parent }
}
let f: F = {
    cp: Child1 //ok
}
Sign up to request clarification or add additional context in comments.

1 Comment

@zenggo if this answer helped you solved it don't forget to mark as answered :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.