-
Notifications
You must be signed in to change notification settings - Fork 328
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
Parsing open-ended unions #665
Comments
I tried your code and it works like a charm. No type errors. I do not understand what the problem is? |
If you look at the type of I think what happens is that the type checker fives If you change console.log('circle:', o.radius); to console.log('circle:', o.radius + 1); you will see a type error. |
Ok I see an error now. The problem in this case is not You can solve this only by decoding in two steps. First strictly with your |
🚀 Feature request
This is a bit of a long shot, as I don't know if this is a fundamental problem in TypeScript. Still this issue ought to be common in parsing JSON from a backend so perhaps it's been addressed in io-ts.
Current Behavior
A common problem in frontend development is handling version skew between the backend and the frontend. This happens e.g. when a released mobile app expects the backend to return one of a union of possible items and the backend adds a new item to the union.
Example: the backend can return either a
Circle
or aRectangle
object, represented using aShape = Circle | Rectangle
union distinguished by akind
field. The server adds aHexagon
shape, distinguished bykind: 'hexagon'
but the frontend code hasn't been updated to handle this.Modelling the problem in io-ts:
The above example fails when parsing a JSON value with unknown
kind
tag.Desired Behavior
We need to be able to express a parser combinator (and thus also the type generated by the generator) that preferentially parses into known types and falls back to a
UnknownRecord
or similar (although we want the unknown record to contain the discriminator field still).Suggested Solution
This is a non-working solution (OK at runtime but with type errors) but it points in a possible direction:
Who does this impact? Who is this for?
Anyone who has a frontend that communicates with a backend, where the frontend and backend might suffer from version skew.
Describe alternatives you've considered
Give up on type checking via parsing and just manually check the discriminator field and then unsafe case the object.
Additional context
Related: microsoft/TypeScript#26277
Your environment
The text was updated successfully, but these errors were encountered: