Decide Optional vs Required Fields in JSON-to-TypeScript
Use json to typescript correctly by distinguishing required, optional, nullable, and never-present fields. Apply the right modifier from the data, not from a guess.
Detailed Explanation
Three Modifiers, Four Field Behaviors
JSON conversion tools often guess wrong about whether a field is optional, required, nullable, or absent. The right call comes from observing several samples, not one.
Sample Evidence
[
{ "id": 1, "name": "Alice", "email": "a@x.com", "phone": "555" },
{ "id": 2, "name": "Bob", "email": "b@x.com", "phone": null },
{ "id": 3, "name": "Carol", "email": "c@x.com" }
]
Generated TypeScript
interface Contact {
id: number; // present in every sample
name: string; // present in every sample
email: string; // present in every sample
phone?: string | null; // sometimes missing, sometimes null, sometimes a string
}
Decision Table
| Observed across samples | Modifier to apply | TypeScript |
|---|---|---|
| Always present, never null | required | field: T |
| Always present, sometimes null | nullable | field: T | null |
| Sometimes absent, never null | optional | field?: T |
| Sometimes absent or null | optional + nullable | field?: T | null |
Why It Matters at the Call Site
const c: Contact = await loadContact();
c.phone.toLowerCase(); // Error: c.phone is string | null | undefined
c.phone?.toLowerCase(); // Safe
If the converter had marked phone as string, every consumer would write code that crashes on the second sample. The optional-plus-nullable modifier forces correct handling.
Generation Workflow
- Feed the converter at least 3-5 representative samples, not just one.
- Toggle "merge keys" so the tool unifies seen variants per field.
- Manually review fields you know are nullable in your domain (timestamps, foreign keys, optional metadata).
- Document edge cases with comments —
// nullable when no payment methodnext topaymentMethod: string | null.
The closer your modifiers match production reality, the fewer runtime surprises survive into your UI.
Use Case
Generating a Contact type from a CRM API where phone numbers can be missing, present, or explicitly null and you need TypeScript to force the right handling at every call site.
Try It — JSON to TypeScript
Related Topics
Handle Optional and Nullable Fields in TypeScript from JSON
Type Refinements
Type ISO Date Strings vs Plain Strings in JSON-to-TypeScript
TypeScript Patterns
Type HTTP PATCH Payload Shapes from JSON
TypeScript Patterns
Generate Literal Status Unions from JSON for State Machines
TypeScript Patterns
Apply Partial, Required, and Readonly to JSON-Generated Types
TypeScript Patterns