Unions and Narrowing 28 exercises
solution

Create New Types By Combining Unions

Let's split the HTTPCode into two types: ErrorCode and SuccessCode.

The ErrorCode type will be a union of the 400 and 500 codes, and the SuccessCode type will be a union of the 200 and 201 codes.


type ErrorCode = "400" | "401" | "404" | "500";
type SuccessCode = "200" | "2

Loading solution

Transcript

00:00 So let's figure this out. This HTTP code, we kind of need to split it into a couple of different types. Let's take all of the error types and let's go type error code equals all of these. So now we've got our error code and this is going to be our success code down here. And now our error case and our success case are going to be pretty easy to type.

00:19 We can replace this with error code and replace this with success code. But how about our HTTP code down the bottom? We can say type HTTP code. And how should we do this? Well, we can say error code or success code.

00:39 So this means it's just combining those two unions together. So now HTTP code can either... God, I'm having a real trouble saying that. It can either be 400 or 201 or 404 or 204. And this means then that it corresponds to this type down there,

00:54 which means that this type check, which has all the 200 and 400s in it, and it works. So this is a really nice way of thinking about unions that you can later combine them together and make these beautiful combinations.