TypeScript Fundamentals Enums
This course has been updated! We now recommend you take the TypeScript Fundamentals, v3 course.
Transcript from the "Enums" Lesson
>> Mike North: Enums are, this is another concept borrowed from other languages, so it is an ordered set of items, members, right, that all belong in sort of a category. So we have here an account type, it could be a checking, a savings, or a money market account. Each has a name and a value.
[00:00:20] So if you console logged these out, you might see 0, 1, and 2. The benefit is they're, at least from type script's perspective when it's checking things, it's not just a 0, a 1, or a 2, it's actually regarded as a member of that set of items. So if you had five or six different enums.
[00:00:42] You can be assured that this number two came from the right collection, right? It sort of has that metadata associated with it. Like, this is a two in the context of account type. And so now, that has to match in order for that type equivalence to be happy.
[00:01:02] Often, we don't care about the value. We just want to know that we're capturing something that belongs to the right enum type or compare two things. Getting the number of members in a type is interesting. So I'm gonna actually show you what this translates to in regular job script.
[00:01:41] And that is pretty cluttered. So let's kinda unzip it a little bit. You can see that this is sort of, it's an array where, or it's an object I should say where if we pass in a number, we got the name of the enum out. And if we pass in the name of the enum, we get the number out.
[00:02:04] So it serves as a mapping in both directions. The consequence of this is, if we want to find the number of members in this thing, we just get the length and divide it by 2. Hopefully, it should be pretty clear as to why. Because, yeah, you're storing two pieces of data per member.
[00:02:23] So if you want to iterate over these things for example, like say, to build a deck of cards, you might want to remember this. I'm the least sneaky instructor ever.