score:3

Accepted answer

I'm guessing you don't want to replace the props and state, because you probably need a common interface to make the parent class work. So you could make your parent class generic, and then merge in the additional pieces of props/state.

class MyComponent<P, S> extends React.Component<ParentProps & P, ParentState & S> {}
//                ^ Generic P is for child props, Generic S is for child state

Example in use:

type ParentProps = { a: number }
type ParentState = { b: number }
class MyComponent<P, S> extends React.Component<ParentProps & P, ParentState & S> {}
let parentComponent = <MyComponent a={1} />

type ChildProps = { c: number }
type ChildState = { d: number }
class ExtendedComponent extends MyComponent<ChildProps, ChildState> {}
let childComponent = <ExtendedComponent a={1} c={2} />

score:0

For anyone searching for this and being stuck at the "EDIT 2" problem, one workaround is to spread the previous state in your setState() call like this.

this.setState(prevState => { return { ...prevState, foo: newFoo }});

It's required so that no matter what is in the S template, it will get spread and won't be overwritten (and with that you can also make generic the Extended component and inherit from that and so on).

You also, if you want to set the state in the constructor, you can do

super(props);
this.state = {
   ...this.state, 
   foo: newFoo
};

With that, the state initialized in the parent class will remain. You can also just override it if you know every fields of the parent's state.


Related Query

More Query from same tag