-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Closed as not planned
Closed as not planned
Copy link
Labels
Not a DefectThis behavior is one of several equally-correct optionsThis behavior is one of several equally-correct options
Description
π Search Terms
discriminated unions, property incompatibility
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries
β― Playground Link
π» Code
type UnionType = "foo" | "bar" | "baz";
type Discriminated =
| {
discriminator: "foo";
}
| {
discriminator: "bar";
};
const expectedError: Discriminated = { discriminator: "foo" as UnionType }
const unexpectedError: Discriminated = { discriminator: "foo" } as { discriminator: UnionType };π Actual behavior
For unexpectedError, this is the compiler message:
Type '{ discriminator: UnionType; }' is not assignable to type 'Discriminated'.
Type '{ discriminator: UnionType; }' is not assignable to type '{ discriminator: "bar"; }'.
Types of property 'discriminator' are incompatible.
Type 'UnionType' is not assignable to type '"bar"'.
Type '"foo"' is not assignable to type '"bar"'.
This error is very misleading since "foo" is not actually the problem here, it's "baz".
In fact the error goes away, if we remove "baz" from the union.
π Expected behavior
For expectedError the compiler states:
Type 'UnionType' is not assignable to type '"foo" | "bar"'.
Type '"baz"' is not assignable to type '"foo" | "bar"'.
Consequently, the correct error message I would expect for unexpectedError is this:
Type '{ discriminator: UnionType; }' is not assignable to type 'Discriminated'.
Type '{ discriminator: UnionType; }' is not assignable to type '{ discriminator: "foo" | "bar"; }'.
Types of property 'discriminator' are incompatible.
Type 'UnionType' is not assignable to type '"foo" | "bar"'.
Type '"baz"' is not assignable to type '"foo" | "bar"'.
Additional information about the issue
This is a simplified example of this issue, which I discovered, when attempting to supply a parameter a function expecting a discriminated union.
The supplied variable had a wider range of possible discriminator values, like shown in this example.
Metadata
Metadata
Assignees
Labels
Not a DefectThis behavior is one of several equally-correct optionsThis behavior is one of several equally-correct options