JSON to TypeScript: Differences, Edge Cases & Pitfalls
Generate TypeScript interfaces from JSON with optionality inference and markers for unions and nested arrays.
Interface accuracy depends entirely on how representative the sample is: a field is required only if it appears in every object, empty arrays give no element type, and literal unions and optionality need manual tuning. It removes typing labour, not type design.
Format Differences
| Aspect | JSON | TypeScript types |
|---|---|---|
| Typing | None; values exist at runtime only | Compile-time checks with IDE hints |
| Optionality | A field may be missing | Explicit with ? or | undefined |
| Literal unions | No such concept | "a" | "b" narrows the allowed values |
| Numbers and strings | Just number/string | Narrowable to literals and template literal types |
| Naming | No type names | Humans supply semantic names; tools emit Root/Item |
| Discriminated unions | Heterogeneous objects in one array | Model with a discriminant property |
| Runtime validation | None | Types are erased at compile time, so validate at runtime too |
| Code size | The data | Type declarations emit no runtime code |
Edge Cases
- A field is required only if present in every sample; one missing sample flips it to optional and loosens the contract.
- JSON null must be written as
| nullexplicitly, or strict mode rejects the assignment. - Dates are plain strings and the type system cannot tell them from any other string; apply a template literal type.
- Integers beyond 2^53 lose precision in JS, so typing them as number hides the bug — use string for that field.
Common Pitfalls
- Committing the generated types as the contract; the loose optionality lets nulls reach production.
- Interfaces all named Root/Item, so six months later nobody knows which type maps to which endpoint.
- Large ID numbers typed as number are damaged on parse while type checking stays silent.
- Relying on types for runtime validation — they vanish after compilation and invalid data still arrives.
Related Tools
- JSON to TypeScriptGenerate TypeScript interfaces from sample JSON with nested types, arrays and optional fields for typing API responses and configuration or payload objects.
- Data Format ConverterConvert between JSON, YAML, TOML, XML and CSV in one place with a single paste and instant preview for seamless multi-format config and data conversion.
- JSON to YAMLConvert JSON data to YAML format with custom indentation and nested object support. Turn verbose JSON configs into clean readable YAML in a couple of seconds.
- Excel to JSONConvert Excel files (xlsx, xls, csv) to JSON format. Supports nested headers, sheet selection and key mapping. Choose the sheet and header row and keep numbers.