There are no errors in the code shown below:
type C = {b: string};
class Class {
data: C;
constructor(data: C) {
this.data = data;
}
test() {
const hack: C & {a?: any} = this.data; //no error
}
}
However, when a generic type is used instead of the actual type, the 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; }'
}
}
Why does this happen? In the second snippet of code, 'C' can be any type. According to duck typing, any type should be compatible with any type plus something optional.