Enum members
- TypeScript course
- Beginner
- Lesson 23/89
- 4 min
Learn enum member access and reverse mapping.
Accessing enum members
You access enum members with dot notation: EnumName.Member. In a numeric enum, this access returns the member's number value. The value is the explicitly assigned number or, otherwise, the auto-incremented number.
enum Yon { Kuzey, Guney }
console.log(Yon.Kuzey); // 0
console.log(Yon.Guney); // 1If a previous member was assigned a value, the next member automatically gets one more.
Reverse mapping
Numeric enums have reverse mapping: you can go from a number to the member name. A usage like Kod[10] returns the name of the member with that value as a string. This feature works only for numeric enums, not for string enums.
enum Kod { A = 10, B }
console.log(Kod[10]); // "A"
console.log(Kod.B); // 11Reverse mapping lets you convert a number back to a name.
Practice Reverse mapping in a color constant
Define a const named Renk mapping Kirmizi to 0 and Mavi to 1. Add reverse mapping by using number values as keys (e.g. key 1 maps to "Mavi"). Print the name obtained via Renk[1] with console.log.
Starter code
// Renk adında bir const tanımla
// Kirmizi 0 ve Mavi 1 ile eşle
// ters eşleme için sayıları da anahtar yap
// Renk[1] ile ismi yazdırSample solution
const Renk = { Kirmizi: 0, Mavi: 1, 0: "Kirmizi", 1: "Mavi" };
console.log(Renk[1]);Expected output
Mavi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>enum Kod { A = 10, B }</code>, what is <code>Kod.B</code>?
- 1
- 11 Correct answer
- 10
- 0
Explanation: Since <code>A = 10</code>, <code>B</code> automatically gets one more, that is <code>11</code>.
2 Find the name via reverse mapping
enum Kod { A = 10, B }
let isim = Kod[____];
enum Kod { A = 10, B }
let isim = Kod[10];
Explanation: Since <code>A = 10</code>, reverse mapping <code>Kod[10]</code> returns <code>"A"</code>; <code>0</code>, <code>1</code> and <code>100</code> do not correspond to any member.
3 Access and reverse mapping
| Term | Meaning |
|---|---|
Yon.Kuzey |
Returns the member's number value |
Kod[10] |
Returns the name via reverse mapping |
Reverse mapping |
Works only for numeric enums |
String enum |
Does not support reverse mapping |