Generate TypeScript Union Types from JSON String Values
Learn how to narrow string fields to string literal union types in TypeScript when converting JSON. Improve type safety beyond plain string.
Detailed Explanation
From Plain Strings to Literal Unions
A plain string type is often too broad. When you see a JSON field that only takes a fixed set of values, converting it to a string literal union is far more precise.
Example JSON
[
{ "id": 1, "status": "active" },
{ "id": 2, "status": "inactive" },
{ "id": 3, "status": "pending" }
]
Generated TypeScript
interface Account {
id: number;
status: "active" | "inactive" | "pending";
}
How the Converter Detects Unions
The tool examines every distinct string value for a given key across all array elements. If the number of unique values is below a configurable threshold (typically 10-20), the converter generates a literal union instead of string. This heuristic prevents generating absurd unions from free-text fields.
Benefits of Literal Unions
- Exhaustive checking —
switchstatements onstatuswill warn you if you forget a case. - Autocompletion — Your editor suggests
"active","inactive", and"pending"when you assign the field. - Refactoring safety — Renaming a status value causes compile errors everywhere it is used.
Extracting the Union
You can also extract the union into a standalone type:
type AccountStatus = "active" | "inactive" | "pending";
interface Account {
id: number;
status: AccountStatus;
}
This is especially useful when the same set of values appears in multiple interfaces (e.g., AccountStatus in Account, AuditLog, Notification).
When Not to Use Unions
If the field accepts user-provided text (names, descriptions, comments), keep it as string. Literal unions are only for enumerated, closed sets.
Use Case
You are building a dashboard that displays order statuses and want compile-time guarantees that your UI code handles every possible status value.
Try It — JSON to TypeScript
Related Topics
Generate TypeScript Enums from Repeated JSON Values
Type Refinements
Convert JSON to TypeScript Discriminated Union Types
Complex Types
Handle Optional and Nullable Fields in TypeScript from JSON
Type Refinements
Convert a Simple JSON Object to a TypeScript Interface
Basic Conversions
Type a Full API Response JSON as TypeScript
Advanced Patterns