Course contentsShow
← TypeScript
Lesson 493 of 1,79612. EnumsFree lesson

Computed Enum Members

Use expressions and constants to compute enum values at compile time with limitations.

Computed Enum Members

You'll learn how TypeScript lets you use expressions to compute enum values at compile time, with important restrictions.

What Are Computed Enum Members?

So far, you've seen enum members with literal values—direct numbers or strings. TypeScript also allows computed members, where the value is determined by a compile-time expression. However, these aren't arbitrary runtime calculations; they're restricted to operations TypeScript can evaluate during compilation.

The Rules

A computed enum member can be:

  • A reference to another enum member (from the same or different enum)
  • A simple arithmetic expression using +, -, *, /, %, <<, >>, >>>, &, |, ^
  • Parentheses to group expressions
enum FileAccess {
  None = 0,
  Read = 1,
  Write = 2,
  ReadWrite = Read | Write,  // Computed: 3
  Extra = ReadWrite + 1      // Computed: 4
}

The Limitations

You cannot use:

  • Function calls
  • Variables from outside the enum
  • Complex runtime operations
  • Template literals
const baseValue = 10;

enum Invalid {
  // Error: Can't reference external variable
  // A = baseValue,
  
  // Error: Can't call functions
  // B = Math.floor(3.7)
}

Think of computed members like a spreadsheet formula—you can reference other cells and do basic math, but you can't run arbitrary JavaScript.

Practical Use

Computed members shine when creating bitwise flags or derived constants:

enum Permission {
  None = 0,
  Read = 1 << 0,     // 1
  Write = 1 << 1,    // 2
  Execute = 1 << 2,  // 4
  All = Read | Write | Execute  // 7
}

Key Takeaway: Computed enum members let you derive values from other members and constants using basic expressions, but only with operations TypeScript can evaluate at compile time—no runtime code allowed.