Either/Or types in TypeScript

Mae Capozzi · September 25, 2020How to create a TypeScript either/or type using union types and the never keyword to enforce that an object has one property or the other, but not both

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 one and theOther.

In this case, if we don't enforce that consumers should only pass a parameter with either one or theOther we run into a less-than-ideal scenario. If both one and 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 one and theOther, we don't get an error:


When we enforce the "either/or" type

We can use a combination of TypeScript's never and union types to enforce that a parameter can either include one, or theOther, and never both.


Let's take a look at what this looks like when someone tries to pass a parameter with both one and theOther to the oneOrTheOther function! If we call oneOrTheOther with an invalid parameter:


we get the following error:

Continue Reading

aiobservabilitydeveloper-tools

AI agents removed the friction from writing telemetry

I used to avoid adding telemetry because it felt like tedious busywork. Now with Claude handling the OpenTelemetry boilerplate, I'm instrumenting everything.

Read Post