-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Discriminated union types better error reporting #10867
Labels
Committed
The team has roadmapped this issue
Fixed
A PR has been merged for this issue
Suggestion
An idea for TypeScript
Milestone
Comments
There's another recent issue #10849 that talks about this and other discriminated unions issues. Perhaps one could be merged into the other? |
Yes, this is a subset of the issue #10849 that reported a few days back. |
Work item for 2.2: Figure out how to detect discriminated unions and report errors based on a matched discriminant field |
sandersn
added a commit
that referenced
this issue
Feb 10, 2017
Assignability errors for discriminated unions now check the value of the discriminant to decide which member of the union to check for assignability. Previously, assignability didn't know about discriminated unions and would check every member, issuing errors for the last member of the union if assignability failed. For example: ```ts type Square = { kind: "sq", size: number } type Rectangle = { kind: "rt", x: number, y: number } type Circle = { kind: "cr", radius: number } type Shape = | Square | Rectangle | Circle; let shape: Shape = { kind: "sq", x: 12, y: 13, } ``` `typeRelatedToSomeType` now checks whether each property in the source type is a discriminant. It finds `kind` and proceeds to look for the type in the target union that has `kind: "sq"`. If it finds it, which it does in this example (`Square`), then it checks only assignbility to `Square`. The result is that the error now says that property 'size' is missing in type `{ kind: "sq", x: number, y: number }` instead of saying that that "sq" is not assignable to type "cr" like it did before. Fixes #10867
Fix is up at #14006 |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Labels
Committed
The team has roadmapped this issue
Fixed
A PR has been merged for this issue
Suggestion
An idea for TypeScript
This the example from docs:

So we create object with type
Shape
of kindsquare
and try to pass incorrect other props (for this kind), and TS emits the error that object is no assignable to last type that is in union (Circle
in this case). I believe it would be better if TS would recoginze that we are trying to makeSquare
type in this case and emitted corresponding error message.The text was updated successfully, but these errors were encountered: