How to convert JSON to TypeScript
- Paste an API response or fixture. To combine separate responses, switch to JSON Lines and enter one complete value per line.
- Name the root type and choose interfaces or type aliases for objects. Arrays, primitives and unions at the root use a type alias.
- Generate the types, review the inferred fields against your API contract, then copy the code or download a .ts file.
Example: missing fields, null and mixed arrays
[{"id":1,"email":null},{"id":"2","name":"Lin"}]
export type ApiResponse = ApiResponseItem[];
export interface ApiResponseItem {
id: number | string;
email?: null;
name?: string;
}
The two objects are merged into one item type. The id field becomes number | string. Both email and name are optional because each is missing from one object. When email is present in these samples, its type is null.
An array with only empty samples becomes unknown[]. If another sample supplies elements at the same position, those elements are used to infer the array type.
Frequently asked questions
How do optional fields differ from nullable fields?
A missing property adds ? when other objects at the same position contain it. An explicit null adds null to the property type. A property present in every sample stays required even when some values are null.
When should I add more JSON samples?
Include examples with different responses, empty collections and optional fields. One sample only shows the values it contains. Object shapes at the same position are merged, so review relationships between fields if your API uses discriminated unions.
Does the generated TypeScript validate API responses?
The generated declarations describe the observed shape for TypeScript. To validate new data while your program runs, check it against a runtime schema or your API contract.
What input can the converter handle?
The converter accepts standard JSON values and JSON Lines. It processes up to 200,000 characters and 40 levels of nesting in your browser. JSON Lines mode accepts up to 100 nonblank lines.