Closed
Description
π Search Terms
"5.1", "type union"
π Version & Regression Information
- This changed between versions 5.0 and 5.1 (based on playground version selection)
β― Playground Link
π» Code
enum MyEnum {
A = 1,
B = 2
}
type TypeA = {
kind: MyEnum.A;
id?: number;
};
type TypeB = {
kind: MyEnum.B;
}
& (
{
id?: undefined;
}
|
{
id: number;
}
);
type MyType = TypeA | TypeB;
function Something(a: MyType): void {}
Something({ kind: MyEnum.A });
Something({ kind: MyEnum.B });
Something({ kind: MyEnum.A, id: undefined });
Something({ kind: MyEnum.A, id: 1 });
Something({ kind: MyEnum.B, id: undefined });
Something({ kind: MyEnum.B, id: 1 });
function Indirect(kind: MyEnum, id?: number): void {
Something({
kind,
id
});
}
function Indirect2(kind: MyEnum, id?: number): void {
switch (kind) {
case MyEnum.A:
case MyEnum.B:
Something({
kind,
id
});
break;
default:
break;
}
}
function Indirect3(kind: MyEnum, id?: number): void {
switch (kind) {
case MyEnum.A:
Something({
kind,
id
});
break;
case MyEnum.B:
Something({
kind,
id
});
break;
default:
break;
}
}
π Actual behavior
Indirect and Indirect2 report an error, while Indirect3 does not even though the call signature is identical (there is just an extra type check)
Argument of type '{ kind: MyEnum; id: number | undefined; }' is not assignable to parameter of type 'MyType'.
Types of property 'kind' are incompatible.
Type 'MyEnum' is not assignable to type 'MyEnum.A'.(2345)
π Expected behavior
All 3 versions of Indirect behave the same and produce no errors
Additional information about the issue
We are currently on 4.9 and are preparing to migrate to 5.5 once it goes GA.
In our codebase TypeB has some additional required fields when id is a numer, hence the union.
I did observe that a simpler call signature (using only the discriminator) also fails in 4.9 and 5.0
Something({ kind });