Unions and Narrowing 29 exercises
Problem

Combining Union Types in TypeScript

Let's revisit a previous example where we dealt with HTTP status codes:


type HttpCode = "400" | "401" | "404" | "500" | "200" | "201" | "204";
const handleErrorCase = (code: string) => {
// An imaginary function where we only handle the errors
type test = Expect<Equal<typeof code, "40

Loading exercise

Transcript

00:00 In this exercise, we have a few different functions here. We have a handleErrorCase function, which takes in a code which is currently typed as string. And then we have a handleSuccessCase function, which takes in a code currently typed as string. And we have HTTP code at the top, which is a union of a bunch of different codes,

00:19 a bunch of 400 codes and 500 codes. And then there's some 200 codes there too. In REST, which is what this is kind of mimicking, 200 codes are considered success cases and 400 and 500 codes are considered error cases. So what we want to do is we kind of want to split this up

00:37 into two different, like two or a few different types here. Because our error case, we want it to handle just the error cases and our success case, we just want it to handle the success case. You can see inside the tests, inside the functions, it's expecting code to equal 400s or the 500s. And in the success case,

00:55 it's expecting code to equal 200s just there. So your job is to try to find a way of changing this type so that we can have maybe several type aliases that all correspond to each one without having too much duplication. Ideally, we don't want sort of multiple of 400 in there

01:15 because the handleAllCase is working perfectly well, but it's just the handleErrorCase and handleSuccessCase that are currently breaking. So the main little puzzle here is working out how to combine different unions together. And I'll leave that one with you. Good luck.