Using Discriminated Unions in TypeScript for Safer API Responses

Sushek Tamrakar
2 min readFeb 28, 2024

--

Lets get started with a TypeScript tip I learned a while ago. It’s been really simple and useful for my work and personal projects.

Lets consider the two TypeScript types for the current state of our API:

type SuccessResponse = {
state: 'success'
loading: false
}

type ErrorResponse = {
state: 'error'
message: 'Something went error'
}

// This means type can be either an SuccessResponse or a ErrorResponse
type ApiResponse = SuccessResponse | ErrorResponse

By typing our API response this way, we can easily make our code fully type-safe!

const ValidateApiResponse = {data: ApiResponse) => {
if (data.state == 'error') {
// Here we can know the message is defined now, because if there is an
// "error" state, there must be a message!
const message = data.message
}
}

Now, why are we just assuming that the ‘data.state’ property always exists? The reason is that the state property is present both in the success, but also in the error object. So either way, this property will be set and allow us to check its value.

How cool is that? Because an error property, according to our ‘ErrorState’ type, always goes together with a message, we can now guarantee access to that message inside our if-statement. TypeScript realizes this and automagically narrows down the type our data can have inside of the if-statement.

This is also called Discriminated unions.

Discriminated unions in TypeScript are a fancy way of setting this up. You define types that say, “Hey, if the state is 'success', expect this kind of information. But if the state is 'error', expect a different kind of information, always including a message about what went wrong."

When you check the state property, TypeScript is smart enough to understand what type of information you're dealing with without you having to repeatedly tell it. If you see a 'success', TypeScript knows you're dealing with a success type of information. If you see an 'error', it knows there's also a message explaining the problem.

This trick makes your code cleaner and safer. You won’t accidentally try to read a thank-you note that isn’t there, because TypeScript knows the type of response you’re dealing with and ensures you handle it correctly.

Hope you guys find this small tips helpful. See you in next topic.

Happy Coding!!!

--

--

Sushek Tamrakar
Sushek Tamrakar

Written by Sushek Tamrakar

I’m Software Developer currently using Django and NextJs

No responses yet