Blog
JavaScript

Enums in TypeScript: Defining Named Constants

Organize related values with enum types

TypeScript Enums allows you to create a list of constants (unchanging variables) and give them easy-to-remember names. These names make your code easier to read and understand by grouping related values together under one name. Enums can use both numbers and text, so you can choose what works best for your code.

  • Easy-to-remember names: Replace hard-to-understand numbers or strings with meaningful names.
  • Group-related values: Keep similar values organized under a single identifier for better code structure.

Types of Enums in TypeScript

TypeScript provides two main types of enums: Numeric and String enums.

1. Numeric Enums

Numeric enums are the default in TypeScript. Each member of a numeric enum is assigned a numeric value, starting from 0 by default, but you can customize these values as needed.

Default Numeric Enums: In default numeric enums, the first member is assigned the value 0, and each subsequent member is incremented by 1.

typescript

Output:

  • First member is 0: Direction.Up is 0.
  • Auto-increment: Direction.Down is 1, Direction.Left is 2, and so on.

Initialized Numeric Enums: You can assign a specific value to the first member, and subsequent members will auto-increment from that value.

typescript

Output:

  • Custom start: Direction.Up is set to 1.
  • Auto-increment continues: Direction.Down becomes 2, Direction.Left becomes 3, etc.

Fully Initialized Numeric Enums:

Each member can be assigned a unique numeric value, independent of its position.

typescript

Output:

  • Each member has a specific value: Up is 1, Down is 3, Left is 5, and Right is 7.
  • Logging Direction.Up outputs its assigned value, 1.

2. String Enums

String enums allow you to assign string values to each member, providing meaningful names that enhance code clarity.

typescript

Output:

  • Each member is assigned a descriptive string value.
  • Logging Direction.Up outputs "UP".

3. Heterogeneous Enums

TypeScript also supports heterogeneous enums, where you can mix both numeric and string values in the same enum. However, this is not commonly used because it can make the code less consistent and harder to maintain.

typescript

Output:

  • Mix of numbers and strings: Members can have either numeric or string values.
  • Less common: Not recommended for most cases as it reduces consistency.
avatar

0 Comments

No comments

Leave a Reply

avatar

Recent Post

Related Topics

    Feeds

      Don't miss what's next 👋

      Enjoyed this content? Leave your email to get notified when we publish new insights, tutorials, and updates — no spam, ever.