TypeScript Enums

Enums (short for enumerations) in TypeScript allow developers to define a set of named constants. They provide a convenient way to organize related values and make code more readable and maintainable. Enums allow a developer to define a set of named constants that can be numeric or string-based.

Basic Enum Usage

Here’s a simple example of a numeric enum:

enum Color {
  Red,    // 0
  Green,  // 1
  Blue    // 2
}

let favoriteColor: Color = Color.Green;
console.log(favoriteColor); // 1
console.log(Color[1]);      // Green

By default, enums are zero-based, meaning the first value is assigned 0, the second 1, and so on.

String Enums

TypeScript also supports string-based enums, which are more descriptive and debugger-friendly:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

let move: Direction = Direction.Up;
console.log(move); // UP

Use Enums with Functions

Enums can be effectively used with functions to create more readable and type-safe code. Here’s an example:

enum UserRole {
  Admin = "ADMIN",
  Editor = "EDITOR",
  Viewer = "VIEWER"
}

function checkAccess(role: UserRole): boolean {
  switch (role) {
    case UserRole.Admin:
      return true;
    case UserRole.Editor:
      return true;
    default:
      return false;
  }
}

console.log(checkAccess(UserRole.Admin));  // true
console.log(checkAccess(UserRole.Viewer)); // false

Enums in Classes

TypeScript enums can be used within classes to organize code and improve readability:

enum TaskStatus {
  Todo = "TODO",
  InProgress = "IN_PROGRESS",
  Done = "DONE"
}

class Task {
  id: number;
  title: string;
  status: TaskStatus;

  constructor(id: number, title: string) {
    this.id = id;
    this.title = title;
    this.status = TaskStatus.Todo;
  }

  updateStatus(newStatus: TaskStatus): void {
    this.status = newStatus;
  }
}

const task = new Task(1, "Learn TypeScript");
console.log(task.status); // TODO
task.updateStatus(TaskStatus.InProgress);
console.log(task.status); // IN_PROGRESS

Work with Enum Values in TypeScript

Let me explain to you how to work with enum values.

Check if an Enum Contains a Value

To check if an enum contains a specific value, you can use various approaches:

enum Fruit {
  Apple = "APPLE",
  Banana = "BANANA",
  Orange = "ORANGE"
}

// Method 1: Using Object.values
function isValidFruit(value: string): boolean {
  return Object.values(Fruit).includes(value as Fruit);
}

console.log(isValidFruit("APPLE"));  // true
console.log(isValidFruit("GRAPE"));  // false

// Method 2: Using type assertion
function isFruit(value: string): value is Fruit {
  return Object.values(Fruit).includes(value as Fruit);
}

Get the Enum Key by Value

To get an enum key by its value, you can use this approach:

enum HttpStatus {
  OK = 200,
  NotFound = 404,
  ServerError = 500
}

function getKeyByValue(enumObj: any, value: number | string): string | undefined {
  return Object.keys(enumObj).find(key => enumObj[key] === value);
}

console.log(getKeyByValue(HttpStatus, 404)); // NotFound

Create Custom Types from Enum Values

You can create custom types from enum values to ensure type safety:

enum PaymentMethod {
  CreditCard = "CREDIT_CARD",
  PayPal = "PAYPAL",
  BankTransfer = "BANK_TRANSFER"
}

type PaymentMethodType = keyof typeof PaymentMethod;
// Equivalent to: type PaymentMethodType = "CreditCard" | "PayPal" | "BankTransfer"

function processPayment(method: PaymentMethodType): void {
  console.log(`Processing payment via ${PaymentMethod[method]}`);
}

processPayment("CreditCard"); // Valid
// processPayment("Cash");    // Error: Argument of type '"Cash"' is not assignable to parameter of type 'PaymentMethodType'

Compare Enums in TypeScript

Comparing enum values in TypeScript can be done using the equality operators:

enum Size {
  Small,
  Medium,
  Large
}

let mySize = Size.Medium;

// Using double equals (==)
if (mySize == Size.Medium) {
  console.log("Size is medium");
}

// Using triple equals (===)
if (mySize === Size.Medium) {
  console.log("Size is strictly medium");
}

Enums vs String Literal Unions

When choosing between enums and string literal unions, consider their different characteristics:

// Using enum
enum Theme {
  Light = "light",
  Dark = "dark"
}

// Using string literal union
type ThemeType = "light" | "dark";

// Enum approach
function setTheme(theme: Theme) {
  document.body.className = theme;
}

// String literal union approach
function setThemeType(theme: ThemeType) {
  document.body.className = theme;
}

String literal unions are simpler and better for one-time use cases, while enums provide more structure and are useful for collections of related options.

Avoid Duplicate Enum Values

Avoiding duplicate enum values is important for maintaining clarity and preventing unexpected behavior:

// Problematic: duplicated values
enum ApiStatus {
  Success = 200,
  Created = 201,
  OK = 200 // Duplicate value
}

// Better approach: ensure unique values
enum HttpStatus {
  OK = 200,
  Created = 201,
  Accepted = 202
}

Check Out the TypeScript Enums Tutorials

Here are some TypeScript Enum tutorials.

Conclusion

TypeScript enums are a powerful feature that can make your code more readable, maintainable, and type-safe. Whether you’re using numeric or string-based enums, they provide a clean way to define sets of related constants and use them throughout your application. By understanding the various ways to work with enums, you can leverage their full potential in your TypeScript projects.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

Let’s be friends

Be the first to know about sales and special discounts.