0

I'm trying to use Generic interfaces for my classes. My Class has a generic Type which Extends an interface and a class variable with that Type. But as soon as I try to assign a value to that variable the compiler gives me an error.(Example: Class A)

When I don't extend the Generic Type it works. (Example: Class B)

//Generic Classes problem
interface MyStateInterface {
    test?: number
}

class A<IState extends MyStateInterface> {
    protected state: IState;

    constructor() {
        // Error here
        this.state = {
            test: 1
        };
    }
}

class B<IState extends MyStateInterface> {
    protected state: MyStateInterface;

    constructor() {
        this.state = {
            test: 1
        };
    }
}

Does anyone have a solution to this problem?

1 Answer 1

4
class A<IState extends MyStateInterface> {
    protected state: IState;

    constructor() {
        this.state = { ...

What you've said is that IState extends MyStateInterface. This means someone could instantiate A with a more specific type than MyStateInterface. Specifically, someone could add new required properties:

interface MyCoolState extends MyStateInterface {
  required: string;
}
let x = new A<MyCoolState>();

When this happens, your constructor code breaks the contract of MyCoolState by initializing state with a value that lacks required.

How you fix this depends on what you're trying to do. Usually when people find themselves in this situation, the correct thing is to not be generic at all -- it is already legal for subclasses to override state with a more-derived type, so if that's the behavior you're trying to enable, you don't need generics at all.

Sign up to request clarification or add additional context in comments.

Comments

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.