score:4

Accepted answer

You can't assign an object literal to something that is of a generic type. The generic type constrain defines the minimal set of properties that S can have, but it could have more properties, some of them mandatory, consider this derived class:

class MyStatefulComponent extends StatefulComponent<StatefulProps, StatefulState & { newMandatoryProp: number }> {
    constructor(p: StatefulProps){
        super(p);
        this.state.newMandatoryProp // will be undefined beacuse the base class did not initailize it correctly 
    }
    generateState(stateName: string, stateParam?: any): object { return null as any }
}

You can use a type assertion to do this anyway but it is not type safe:

export default abstract class StatefulComponent<P extends StatefulProps, S extends StatefulState> extends React.Component<P, S> {
    constructor(props: P) {
        super(props);

        this.state = {
            machine: {},
            name: '',
        } as S;
    }
}

You could also have an abstract method for creating the state, and pass responsibility of creating the full state object to the derived class.


Related Query

More Query from same tag