0
0
Typescriptprogramming~5 mins

Heterogeneous enums in Typescript

Choose your learning style9 modes available
Introduction

Heterogeneous enums let you mix numbers and strings in one group. This helps when you want different types of values together but still keep them organized.

When you want to label options with both numbers and words.
When some values need to be readable text and others need to be numeric codes.
When working with APIs that expect mixed types for certain settings.
When you want clear names but also need to store different kinds of data in one place.
Syntax
Typescript
enum Example {
  First = 1,
  Second = "two",
  Third = 3
}

You can assign numbers or strings to enum members.

Mixing types is allowed but use it carefully to avoid confusion.

Examples
This enum mixes numbers and strings for different statuses.
Typescript
enum Status {
  Active = 1,
  Inactive = "no",
  Pending = 3
}
Here, some responses are strings and one is a number.
Typescript
enum Response {
  Yes = "YES",
  No = 0,
  Maybe = "MAYBE"
}
Sample Program

This program shows how to use a heterogeneous enum and print its values.

Typescript
enum Mixed {
  Ok = 200,
  NotFound = "404",
  Error = 500
}

console.log(Mixed.Ok);       // 200
console.log(Mixed.NotFound); // "404"
console.log(Mixed.Error);    // 500
OutputSuccess
Important Notes

Heterogeneous enums can be confusing if overused, so keep them simple.

Use string values when you want readable output, numbers when you need codes.

Summary

Heterogeneous enums mix numbers and strings in one enum.

They help organize related but different types of values.

Use them to label options clearly with mixed data types.