Generate TypeScript Enums from Repeated JSON Values
Learn how to generate TypeScript enums from JSON fields that contain repeated categorical values. Compare enums vs string literal unions.
Detailed Explanation
Enums from JSON Data
When a JSON field contains a small set of categorical values, you may prefer a TypeScript enum over a string literal union for its runtime representation and reverse-mapping capabilities.
Example JSON
[
{ "name": "Bug Report", "priority": "high" },
{ "name": "Feature Request", "priority": "medium" },
{ "name": "Documentation", "priority": "low" }
]
Generated TypeScript (enum style)
enum Priority {
High = "high",
Medium = "medium",
Low = "low",
}
interface Ticket {
name: string;
priority: Priority;
}
Enum vs String Literal Union
| Feature | Enum | String literal union |
|---|---|---|
| Runtime value | Yes (compiled to object) | No (erased at compile time) |
| Reverse mapping | Yes (for numeric enums) | No |
| Tree-shaking | Partial | Full |
| Iterable at runtime | Yes (Object.values) |
No |
| Compatibility with plain JS | Requires compilation | Works as-is |
When to Choose Enums
- You need to iterate over all possible values at runtime (e.g., populating a dropdown).
- You want to import the enum in both type and value positions.
- Your codebase convention already uses enums.
When to Prefer Unions
- You want the smallest possible bundle (unions are erased by TypeScript).
- You are using
as constassertions for similar behavior. - You need compatibility with plain JavaScript files.
Const Enums
const enum Priority {
High = "high",
Medium = "medium",
Low = "low",
}
const enum is fully inlined at compile time — no runtime object is emitted. However, it is incompatible with --isolatedModules (used by Babel, SWC, and esbuild), so most modern projects avoid it.
Use Case
You are building a ticket management system and need the priority values available both as types and as runtime values for rendering dropdowns and filter chips.
Try It — JSON to TypeScript
Related Topics
Generate TypeScript Union Types from JSON String Values
Type Refinements
Convert JSON to TypeScript Discriminated Union Types
Complex Types
Convert a Simple JSON Object to a TypeScript Interface
Basic Conversions
Type a Full API Response JSON as TypeScript
Advanced Patterns
Use TypeScript Utility Types with JSON-Generated Interfaces
Complex Types