TypeScript Only Features 9 exercises
solution

Creating a String Enum in TypeScript

Creating an enum of strings has a different syntax than creating an object. Instead of using the : syntax, we use the = syntax:


enum Method {
GET = "GET",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
}

Like before, once the enum is created we can refer to it by nam

Loading solution

Transcript

00:00 Okay, so method we know probably is going to need to change to an enum, but we've only seen so far numeric enums. How do we handle enums which have strings in them? Well, we can't use this kind of like colon syntax here, but we can use the equal syntax, just like we did when we had 0, 1, 2, 3, 4.

00:19 Here we can do get, post, put, and delete. So how then do we handle the method? Well, we can derive one from the other. So we can say method is now method. And this is really cool. This means that we now have this enum method that is the only thing that can be passed into our request.

00:39 We can't use the string equivalence here. So we can't say argument of type get is not a site, like we just can't do it. We don't even get autocomplete for this stuff. You hover over it and it says you have to use a method. And so you import method and you say method.get, post, put, delete. Is this good?

00:58 I mean, some of you might be going, wow, that sounds fantastic. I really want to make sure people are constrained to only using this enum that I've provided, because otherwise it's going to be a little bit, sort of be very messy if I need to refactor one of these, let's say.

01:16 If I need to change put to patch, I can just literally do it right here and then boom, we're good to go. But it does get a little bit annoying when you use this kind of, this method, when you have an enum down here, which is method two, which has exactly the same values, get, post, put, and delete.

01:34 You can't use them even though nothing will break at runtime. So it's interesting. Enums kind of break a little bit of an assumption that we have about TypeScript, which is that TypeScript uses duck typing, which is if it looks like a duck, if it quacks like a duck, then it's a duck. And here, if it looks like a get,

01:53 if it quacks like a get, it should be passed as a get. And so enums are a little bit funky in that way where they don't let you combine with other enums or don't let you, it doesn't really behave as you expect. Or at least for me, it feels a little bit sort of strange

02:10 that you would have to import this specific enum for this specific case. Whereas I would usually prefer to just say get or post or put or delete. That seems fine to me. But for those of you who are disagreeing with me, who say, yes, this seems fantastic, then string enums are there for you to use.