What is a string enum, and how does it differ from a numeric enum?
Short answer
A string enum explicitly assigns a distinct string literal to each member (no auto-incrementing), which makes debugging easier since logged/serialized values are meaningful text rather than opaque numbers, and prevents accidental numeric type coercion between unrelated enums.
Advertisement
AModel answer
A string enum explicitly assigns a distinct string literal to each member (no auto-incrementing), which makes debugging easier since logged/serialized values are meaningful text rather than opaque numbers, and prevents accidental numeric type coercion between unrelated enums.
enum Status {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
Pending = 'PENDING'
}
console.log(Status.Active); // 'ACTIVE'Real-world example
Representing an order or subscription status where the readable string value is also what gets sent to or received from an API.
Likely follow-ups
- Can string enum members reference other members' values automatically, the way numeric enums can compute from a previous value?
Related topics