Loading
Current section: 8. Enums 4 exercises
solution

Enum Vs Union

Transcript

00:00 Alright. Now let's jump into this. Let's take this log level thing. And, actually, let's just show you what it looks like when I say log with enum. Alright.

00:08 So we have to do debug log level dot debug, debug message. Alright. And so it works and it's fine and it's whatever. You have to reference log level. You can't just say, debug because you're gonna get an error because this is expecting the log level.

00:22 It technically does work but you cannot, just rely on that because type TypeScript is not gonna like it. So here's what we're gonna do instead. We're gonna comment this out and we're gonna make a type log level and then we're gonna comment this out and we'll make a function that is log with union. So it's basically the same thing. It's just, you know, they're not named properties or anything like that.

00:45 But the Like, your experience in using it is pretty much the same except you don't have to import some value or some enum somewhere you can literally just use the string and you still get autocomplete on all of this stuff. You get type safety, from all of that. So there's not really any difference except that you don't have to bother importing stuff and the resulting generated code doesn't have the, extra stuff. So if we take a look at, the TypeScript playground here again, with our solution, our, level right here with the, types, or that union, that gets completely stripped away. The, message with the type string also stripped away.

01:26 All that's left is just JavaScript stuff and it doesn't have to have all the enums stuff. Whereas, if we back this up till, we have this, right there. Copy that. Paste that in. Look at all that extra stuff it has to throw in there to make this work.

01:40 I'm just not a fan. Not a fan at all. Much prefer this. It's just it's simple. It's clean.

01:47 It's nice. So, you make your decision, but I am gonna just go with my unions all the time. I'm a big fan of that instead. Alright. Hope you enjoyed that one.

01:58 Well done.