TypeScript 7 reference · Type Operators and Keywords
TypeScript enum Keyword
Define a set of named constants. Prefer union types or 'as const' objects in new code; use enums when you need a runtime object.
TypeScript 7 Since 1.0
Examples
enum Status {
Draft = "draft",
Published = "published",
}
function label(s: Status) {
return s === Status.Published ? "Live" : "Not live";
}
console.log(label(Status.Published), Object.values(Status));
Output
Live [ 'draft', 'published' ]
const Status = { Draft: "draft", Published: "published" } as const;
type Status = (typeof Status)[keyof typeof Status];
const s: Status = Status.Draft;
console.log(s);
Output
draft
Numeric enums allow reverse lookups and accept any number, which hides bugs; string enums or as const objects are safer. TypeScript's erasableSyntaxOnly option (and Node's built-in type stripping) disallow enums because they generate runtime code.
Version history
| Version | Change |
|---|---|
| TypeScript 1.0 | Added |
Related
as const· Make a value deeply read-only with literal types: strings stay 'admin' instead of string, arrays become readonly tuples.- TypeScript keyof, typeof and Indexed Access · tutorial