DEV Community

Cover image for πŸ“š TypeScript Enums and Advanced Usage
Artem Turlenko
Artem Turlenko

Posted on

1

πŸ“š TypeScript Enums and Advanced Usage

Enums are a powerful feature of TypeScript, providing an easy way to define named constants that make your code more readable and maintainable. This article explores both basic and advanced usages of enums, including practical examples and best practices.


What are Enums in TypeScript?

Enums (enumerations) are a way to organize collections of related values as named constants, enhancing code clarity and preventing the use of magic numbers or strings.

Basic Enum Example:

enum Direction {
  Up,
  Down,
  Left,
  Right
}

let move: Direction = Direction.Up;
console.log(move); // Output: 0
Enter fullscreen mode Exit fullscreen mode

Numeric vs. String Enums

Numeric Enums:

By default, enums start numbering at 0, but you can customize this:

enum Status {
  Pending = 1,
  InProgress,
  Completed
}

console.log(Status.InProgress); // Output: 2
Enter fullscreen mode Exit fullscreen mode

String Enums:

Useful for debugging and readability:

enum LogLevel {
  ERROR = "ERROR",
  WARN = "WARN",
  INFO = "INFO"
}

console.log(LogLevel.ERROR); // Output: "ERROR"
Enter fullscreen mode Exit fullscreen mode

Advanced Enum Usage

Enum as Types

Enums can be directly used as types in function parameters, promoting type safety:

enum UserRole {
  Admin,
  User,
  Guest
}

function setUserRole(role: UserRole) {
  // implementation
}

setUserRole(UserRole.Admin); // Correct usage
// setUserRole("Admin"); // Error
Enter fullscreen mode Exit fullscreen mode

Const Enums

Const enums are completely removed during compilation, improving performance:

const enum Color {
  Red,
  Green,
  Blue
}

let favoriteColor = Color.Blue;
console.log(favoriteColor); // Output: 2 (inlined during compilation)
Enter fullscreen mode Exit fullscreen mode

Enum with Bitwise Operators

Enums can represent bit flags, providing efficient ways to combine multiple settings:

enum Permissions {
  Read = 1 << 0,
  Write = 1 << 1,
  Execute = 1 << 2
}

let userPermissions = Permissions.Read | Permissions.Write;

// Check permissions
let canExecute = (userPermissions & Permissions.Execute) === Permissions.Execute;
console.log(canExecute); // false
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Prefer string enums for improved readability.
  • Use const enums when performance optimization is critical.
  • Clearly document the intent behind your enums, especially when used with bitwise operations.

Enums offer clarity, type safety, and performance improvements to your TypeScript applications.

Have you used enums in an interesting way? Share your experiences in the comments below! πŸš€

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay