Trung BìnhTypeScript iconTypeScript

Enum trong TypeScript là gì? Numeric vs string enum khác nhau thế nào?

  • Enum khai báo tập hợp named constants.
  • Numeric enum tự động assign 0,1,2... có reverse lookup nhưng gây footgun (Direction[0] = 'Up').
  • String enum cần gán tường minh, dễ debug hơn, không có reverse lookup.
typescript
enum Direction { Up, Down } // numeric: Up=0, Down=1
Direction[0] // "Up" — reverse lookup

enum Status { Active = 'ACTIVE', Inactive = 'INACTIVE' } // string

// Lưu ý 2024+: TS community khuyến nghị dùng const object thay enum
// vì tree-shaking tốt hơn và không sinh runtime code thừa
const Direction = { Up: 'up', Down: 'down' } as const;
type Direction = typeof Direction[keyof typeof Direction];

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript