目录

Enums

An enum is a user-defined type containing a finite set of named constant values. Its main purpose is to replace magic numbers or strings with meaningful names, making code clearer, more readable, and easier to maintain.

Defining and Using Enums

ArkTS supports two forms of enums: numeric enums and string enums.

[h2]Defining Simple Enums

Define an enum with the enum keyword, for example:

// Enum definition.
enum Direction {
  Up,
  Down,
  Left,
  Right
}
let direction: Direction = Direction.Up;

This defines the enum type Direction, which contains four members: Up, Down, Left, and Right.

Access these enum members using qualified names, such as Direction.Up.

Use the enum as follows:

// Enum as a function parameter
function declarationMove(direction: Direction): void {
  switch (direction) {
    case Direction.Up:
      console.info('Up');
      break;
    case Direction.Down:
      console.info('Down');
      break;
    case Direction.Left:
      console.info('Left');
      break;
    case Direction.Right:
      console.info('Right');
      break;
  }
}

declarationMove(Direction.Up);  // Up

Enums with Associated Values

Enum members can be explicitly assigned numeric or string associated values for serialization, persistence, or interaction with external APIs.

[h2]Numeric Enums

Members without explicit values automatically receive incrementing numeric values, starting from 0 or continuing from the previous explicit value.

// Numeric enum auto-increment
enum AutoNumberEnum {
  First,    // 0 (automatic)
  Second,   // 1 (automatic)
  Third,    // 2 (automatic)
  Custom = 10,
  Fourth,   // 11 (continues from Custom)
  Fifth     // 12
}

[h2]String Enums

Every member of a string enum must have an explicitly specified associated value. Compared with numeric enums, string enums use readable strings as member values and are suitable for scenarios such as logging and data serialization.

enum StringEnum {
  A = 'A',
  B = 'B',
  C = 'C'
}

[h2]Associated Value Type Constraints

Within an enum, the associated values of all members must have the same type. Mixing strings and numbers causes a compilation error.

enum Mixed {
  No = 0,
  Yes = 'YES'  // Compilation error: inconsistent associated value types.
}

[h2]Mapping Between Associated Values and Enum Members

Numeric enums support obtaining enum member names from associated values, but string enums do not.

enum BiUserRole {
  Admin = 100,
  Moderator = 200,
  User = 300
}

let biRole: BiUserRole = BiUserRole.Admin;     // 100
let biRoleName: string = BiUserRole[100];      // 'Admin'

function getBiRoleName(roleId: number): string | undefined {
  return BiUserRole[roleId];
}

console.info(`${getBiRoleName(100)}`);  // 'Admin'
console.info(`${getBiRoleName(200)}`);  // 'Moderator'

[h2]Using Enum Members as Literal Types

An enum member is a literal type that can restrict a variable or parameter to a specific enum member. The literal types of different members are incompatible. You can also combine multiple members in a union type to restrict the range of allowed values.

// An enum member is a literal type.
enum LitDirection {
  Left,
  Right,
  Up,
  Down
}

// Restrict the variable to a specific enum member.
let litUp: LitDirection.Up = LitDirection.Up;
console.info(`${litUp}`);  // 2

// Literal types of different members are incompatible.
let litDown: LitDirection.Down = LitDirection.Down;
// litUp = litDown;  // Compilation error: type mismatch.

// Use a union of enum member types to restrict parameter values.
type LitHorizontal = LitDirection.Left | LitDirection.Right;

function moveLitHorizontal(dir: LitHorizontal): void {
  console.info(`Horizontal movement: ${dir}`);
}

moveLitHorizontal(LitDirection.Left);  // Horizontal movement: 0
// moveLitHorizontal(LitDirection.Up);  // Compilation error: type mismatch.

const enum

A const enum inlines its member values at compile time and does not generate a runtime enum object. ArkTS supports const enum. However, note that there is a version dependency risk when sharing it across projects (through .d.ts files): the member values of a const enum are inlined into the consumer's code at compile time. If the source definition of the const enum changes, the consumer must recompile to obtain the new values. It is recommended to use const enum within a project and use a regular enum when sharing across projects.

const enum CeConstDirection {
  Up,
  Down
}

let constDir: CeConstDirection = CeConstDirection.Up;
console.info(`${constDir}`); // 0

Using a regular enum instead of a const enum avoids the cross-project pitfalls:

enum CeDirection {
  Up = 0,
  Down = 1
}

let dir: CeDirection = CeDirection.Up;
console.info(`${dir}`);  // 0

Enum Use Cases

Use enums instead of magic strings/numbers to improve code readability and maintainability.

// Counterexample: using magic strings
function getStatusLabel(status: string): string {
  if (status === 'pending') {
    return 'Pending';
  } else if (status === 'active') {
    return 'Active';
  } else if (status === 'completed') {
    return 'Completed';
  }
  return 'Unknown';
}

// Recommended: use an enum
enum OrderStatus {
  Pending = 'pending',
  Active = 'active',
  Completed = 'completed'
}

function getStatusLabelEnum(status: OrderStatus): string {
  switch (status) {
    case OrderStatus.Pending:
      return 'Pending';
    case OrderStatus.Active:
      return 'Active';
    case OrderStatus.Completed:
      return 'Completed';
    default:
      return 'Unknown';
  }
}

// Counterexample: use a magic number.
function getErrorCode(code: number): string {
  if (code === 404) {
    return 'Not Found';
  } else if (code === 401) {
    return 'Unauthorized';
  }
  return 'Unknown';
}

// Recommended: use an enum
enum HttpErrorCode {
  NotFound = 404,
  Unauthorized = 401
}

function getErrorCodeEnum(code: HttpErrorCode): string {
  switch (code) {
    case HttpErrorCode.NotFound:
      return 'Not Found';
    case HttpErrorCode.Unauthorized:
      return 'Unauthorized';
    default:
      return 'Unknown';
  }
}