Closed
Description
Bug Report
π Search Terms
union; widen; type
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about union.
β― Playground Link
Playground link with relevant code
π» Code
The Handbook describes the union type:
A union type is a type formed from two or more other types, representing values that may be any one of those types.
This means if we define type T = A | B
, then its value can be any of A
's values, or any of B
's values. It implicitly means that if a value is not of type A
or B
, it is not a valid T
value.
However, the code below shows that the same value is considered not A
and not B
, but is A | B
. This contradicts the Handbook. One of them needs to changed to match the other. To me, the Handbook seems to make more sense.
type A = { a: number };
type B = { b: number };
const a: A = { a: 0, b: 1 }; // Error, "b" not allowed
const b: B = { a: 0, b: 1 }; // Error, "a" not allowed
const ab: A | B = { a: 0, b: 1 }; // No error, although the value is not a valid A or B
π Actual behavior
A value of A | B
can be neither A
nor B
.
π Expected behavior
A value of A | B
should be either A
or B
.