Jonathan
Jonathan

Reputation: 546

TypeScript Generic Classes: Cannot assign to Generic Type Variable

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?

Upvotes: 0

Views: 1091

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220894

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.

Upvotes: 4

Related Questions