When you consume an API in TypeScript, writing the types by hand from a JSON response is tedious and error-prone. A generator can turn a sample response into interfaces in seconds. It is a great starting point, as long as you understand what it can and can't know.
From JSON to interface
// JSON
{ "id": 7, "name": "Ada", "email": null, "tags": ["a", "b"], "address": { "city": "Pune" } }
// TypeScript
interface Address {
city: string;
}
interface User {
id: number;
name: string;
email: null;
tags: string[];
address: Address;
}Notice email: null. The generator only saw a null, so it can't know the field is usually a string.
What to fix by hand
- Nullable fields: change null to string | null when the value can be either.
- Optional fields: if a key is sometimes missing, mark it with a question mark (email?: string).
- Unions: fields that can hold different types (a number or a string) need a union type.
- Dates: JSON has no date type, so they arrive as strings; convert them explicitly.
- Big numbers: integers beyond 2^53 lose precision in JavaScript; consider strings.
- Enums: fields with a fixed set of values are better typed as string unions ('admin' | 'user').
Interface or type?
For plain object shapes, interface and type behave almost the same. Interfaces can be extended and merged; type aliases can express unions and more complex shapes. Pick one convention and stay consistent.
Types are erased at runtime
- 1Generate an initial interface from a sample response.
- 2Refine nullable, optional, and union fields using the API documentation.
- 3Add runtime validation at the boundary where data enters your app.
- 4Regenerate or update the types when the API changes.
Convert sample data locally: real API responses often contain personal or private information you shouldn't paste into third-party sites.
Frequently asked questions
+Can I generate TypeScript types from JSON automatically?
Yes. A generator infers interfaces from a sample, but review nullable, optional, and union fields yourself.
+Why is my generated field typed as null?
The sample contained null for that field. Change it to the real type, such as string | null.
+Does TypeScript validate API responses at runtime?
No. Types are removed at compile time, so use a validation library or JSON Schema for runtime checks.
+Should I use interface or type?
Either works for object shapes. Use type for unions and interface when you want to extend or merge declarations.
JSON to TypeScript
Free, runs in your browser — nothing you enter is uploaded.