String Enums

Readable Values

In a string enum every member has a string value. Values are readable in logs, databases and JSON, which is why most teams prefer them over numeric enums.

Example

enum OrderStatus {
  Placed = "PLACED",
  Shipped = "SHIPPED",
  Delivered = "DELIVERED",
}

function canCancel(status: OrderStatus): boolean {
  return status === OrderStatus.Placed;
}

const s = OrderStatus.Shipped;
console.log(s);
console.log(canCancel(s), canCancel(OrderStatus.Placed));
console.log(JSON.stringify({ id: 1, status: s }));
console.log(Object.values(OrderStatus));

Output

SHIPPED
false true
{"id":1,"status":"SHIPPED"}
[ 'PLACED', 'SHIPPED', 'DELIVERED' ]

Plain Strings Are Not Accepted

Example

A string enum only accepts its own members, not the matching raw string (TS2345). This is stricter than a literal union and sometimes inconvenient, for example with values from JSON.

enum OrderStatus { Placed = "PLACED", Shipped = "SHIPPED" }

function canCancel(status: OrderStatus): boolean {
  return status === OrderStatus.Placed;
}

canCancel("PLACED");

Compiler output (tsc)

Line 7: error TS2345: Argument of type '"PLACED"' is not assignable to parameter of type 'OrderStatus'.