Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why type assigning works differently when type is actual type vs generic type

Tags:

typescript

The following code does not have any errors:

type C = {b: string};

class Class {
    data: C;
    constructor(data: C) {
        this.data = data;
    }

    test() {
        const hack: C & {a?: any} = this.data; //no error
    }
}

But if I use generic type instead of actual type code does not compile:

class Class<C> {
    data: C;
    constructor(data: C) {
        this.data = data;
    }

    test() {
        const hack: C & {a?: any} = this.data; //TS2322: Type 'C' is not assignable to type 'C & { a?: any; }'
    }
}

Can you explain why? In the second code snippet C can be anything. If I understand duck typing correctly anything should be compatible with anything & something optional.

like image 680
Stanislav Mikheyev Avatar asked Dec 11 '25 11:12

Stanislav Mikheyev


1 Answers

Because you have not constrained the generic type C, which as you mentioned can be anything. In this case, 'anything' include both undefined and null. If you instantiated the class with undefined as the generic type, then it makes sense for the compiler to give you an error, since undefined & {a?: any} is a non-sensical type. Same thing for the types null, never and unknown

If the generic were constrained to be C extends object, C extends string, etc, then the compiler error goes away

like image 158
Paul Huynh Avatar answered Dec 13 '25 10:12

Paul Huynh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!