Type utils for tagged unions #2
robinpokorny
announced in
TIL
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Tagged (aka discriminated) unions are a great way of expressing the business logic in types and making illegal states unrepresentable.
However, working with them could be tricky. That is until I discovered Distributive conditional types.
Let's say we have these types:
I wanted to have a new union type that would only include
name
andpayload
from each member inPet
union. So I usedPick
, but it did not work out as I wanted. It puts all together and creates a union forname
and another one forpayload
.I expected a new tagged union, just with picked properties for each member. To do that you can do the following.
Nice! This is what I wanted. It just takes a bit of TypeScript magic 😅
The
DistributiveKeys
could be also used, as normalkeyof
returns only the common properties.Links:
Beta Was this translation helpful? Give feedback.
All reactions