Either/Or types in TypeScript
TypeScript lets us communicate to other users of a function what can be passed to it. Sometimes, it's straightforward to apply types to the parameter of a function.
Other times, it can be a bit more difficult. One of those cases is when you have what I like to call an "either, or" type. This is when you want to express that users can only pass an object that contains either "this key", or "that key". If a user passes a parameter with both keys, unexpected behavior could happen.
We want to write a type that expresses the following rules:
When we don't enforce the "either/or" type
We'll start by writing out an example that doesn't prevent consumers from passing a parameter that includes both
In this case, if we don't enforce that consumers should only pass a parameter with either
theOther we run into a less-than-ideal scenario. If both
theOther are passed,
one will always be returned, and
theOther will never be returned.
In our initial example, if we try to call
oneOrTheOther with a parameter that includes
theOther, we don't get an error:
When we enforce the "either/or" type
We can use a combination of TypeScript's
union types to enforce that a parameter can either include
theOther, and never both.
Let's take a look at what this looks like when someone tries to pass a parameter with both
theOther to the
oneOrTheOther function! If we call
oneOrTheOther with an invalid parameter:
we get the following error:
Do you want design systems tips and tricks sent to your inbox?