I’m experiencing a type incompatibility error in TypeScript when using a generic type. However, using a conditional type seems to fix the issue, and I don’t fully understand why. Here are the details:
I have defined a type IfAny
and a generic type Box
as follows:
type IfAny<T> = T extends any ? true : false;
type Box<T> = {
value: IfAny<T>;
};
declare let a: Box<number>;
declare let b: Box<string>;
a = b; // Type 'Box<string>' is not assignable to type 'Box<number>'. Type 'string' is not assignable to type 'number'.(2322)
As you can see, I get an error when trying to assign b
to a
, even though both Box<number>
and Box<string>
have the same structure where value is always true
.
However, if I modify the Box
type definition to use a conditional type, the error disappears:
type Box<T> = T extends any ? {
value: IfAny<T>;
} : never;
declare let a: Box<number>;
declare let b: Box<string>;
a = b; // No error
Additionally, when I use type aliases, there is no error:
type A = Box<number>;
type B = Box<string>;
declare let aa: A;
declare let bb: B;
aa = bb; // No error
Playground
Why does using a conditional type fix the type incompatibility error? How does this behavior relate to TypeScript’s handling of generic types and type compatibility?