Skip to content

Discriminated union type #356

Answered by colinhacks
ianduvall asked this question in Q&A
Discussion options

You must be logged in to vote

It's not possible currently, and it's tricky to implement. It's hard to know what the discriminator key should be. I tried to make this work originally, but there are lots of edge cases, e.g. if the type passed into e.is is itself generic:

e.select(e.Shape, shape => ({
  ...e.is(e.Quadrilateral, { ...e.Quadrilateral['*']}),
  ...e.is(e.Square, { ...e.Square['*']}),
}));

You can try using __type__ to differentiate the options at runtime but it won't be reflected in the type.

e.select(e.Shape, shape => ({
  __type__: { name: true },
  ...e.is(e.Quadrilateral, { ...e.Quadrilateral['*']}),
  ...e.is(e.Square, { ...e.Square['*']}),
}));

But the value of __type__.name will never be Quadrilateral,…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by ianduvall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants