CodeBlanks Logo Icon CodeBlanks

String enum

Learn more readable values with string enums.

String enum

In a string enum, each member has a string value and you must assign a string to every member explicitly. At runtime, the member's value is readable text rather than a number.

enum Durum { Acik = "acik", Kapali = "kapali" }
console.log(Durum.Acik);  // "acik"

A string enum produces meaningful values in logs and data transfer.

Why use a string enum?

A string enum gives readable values at runtime. When you log a numeric enum you see a number, but with a string enum the member's meaning appears directly as text. This makes debugging and data sharing easier.

enum Rol { Admin = "admin", Uye = "uye" }
console.log(Rol.Admin);  // "admin"

Seeing meaningful text instead of numbers makes tracing and understanding easier.

Practice Define the role constant

Define a const named Rol mapping Admin to "admin" and Uye to "uye" (string enum behavior). Print the value of Rol.Admin with console.log.

Starter code

index.ts
// Rol adında bir const tanımla
// Admin "admin" ve Uye "uye" ile eşle
// Rol.Admin değerini yazdır

Sample solution

index.ts
const Rol = { Admin: "admin", Uye: "uye" };
console.log(Rol.Admin);

Expected output

admin

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid string enum definition?

  • enum Durum { "acik", "kapali" }
  • enum Durum { Acik, Kapali }
  • enum Durum { Acik = 1, Kapali = 2 }
  • enum Durum { Acik = "acik", Kapali = "kapali" } Correct answer

Explanation: In a string enum, every member must be assigned a string; <code>Acik = "acik", Kapali = "kapali"</code> is the correct definition. The others are either numeric or invalid syntax.

2 Complete the string enum member

Question
enum Renk { Kirmizi = "kirmizi", Mavi = ____ }
Answer
enum Renk { Kirmizi = "kirmizi", Mavi = "mavi" }

Explanation: The <code>Mavi</code> member must have the value <code>"mavi"</code>; <code>"yesil"</code> is the wrong color, <code>"kirmizi"</code> belongs to another member, and <code>"Mavi"</code> is wrong casing.

3 String enum concepts

Term Meaning
enum Durum { A = "a" } String-valued member
String enum Each member must be assigned a string
Durum.Acik Returns a string at runtime
Dize enum Produces a readable value

All lessons in Beginner