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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With