One response is not a contract
Here is the generator run on a single order from GET /api/orders. It is a perfectly good interface — it compiles, it autocompletes, and every field is required because every field was present:
export interface OrderItem {
id: string;
status: string;
total: number;
currency: string;
couponCode: string;
customer: OrderItemCustomer;
items: OrderItemItems[];
shippedAt: string;
}
export interface OrderItemCustomer {
id: string;
email: string;
vip: boolean;
}
export interface OrderItemItems {
sku: string;
quantity: number;
unitPrice: number;
}
export type Order = OrderItem[];Now run the same generator on the same endpoint, with a second order included. Four lines change, and two of them are the difference between working code and a runtime crash:
export interface OrderItem {
id: string;
status: string;
total: number;
currency: string;
couponCode?: string; // was: string
customer: OrderItemCustomer;
items: OrderItemItems[];
shippedAt: string | null; // was: string
}Nothing about the first response was wrong. It simply did not contain a couponCode-less order, or a shipped order that has not shipped. The interface described the sample faithfully and the endpoint inaccurately, which is the normal failure mode of type inference and the reason the number of samples matters more than the quality of the generator.
Six decisions every generator has to make
Every JSON-to-TypeScript converter answers the same six questions. The output looks different mainly because they answer differently — and most of the arguments about which tool is better are really arguments about this table.
| The situation | The choice | What goes wrong |
|---|---|---|
| A key exists in some array elements and not others | Optional, or required | Required compiles and then throws on the record that lacks it. Optional costs one `?.` at the call site. |
| A key holds a number in one record and a string in another | Union, or pick one | Picking one is a guess that the compiler will stop checking. A union is honest and forces a narrowing at the point of use. |
| A key is sometimes null | Union with null, or treat null as absence | null is a value, not a missing key. Collapsing it loses the distinction the API is making. |
| An array is empty in the sample | unknown, or invented element type | An empty array says nothing about its elements. Guessing produces a type nobody verified. |
| An object appears at two different paths | One shared type, or one per path | Shared types read better but couple two unrelated shapes: change one and the other follows. |
| The root is an array rather than an object | Type alias, or a wrapper interface | A wrapper (`{ data: Order[] }`) that the API never sends is a lie that leaks into every call site. |
The first row is the one that bites. A converter that reads only the first array element — which several popular tools do — will mark every field required, and it will do so silently. The generated file looks correct right up until the endpoint returns a record that does not match the one you happened to paste.
Merging samples is the whole trick
The alternative is to infer each element and merge the results, so a key present in one record and absent in another becomes optional instead of required. That is what the JSON to TypeScript tool does, and it is why pasting an array of responses gives a better type than pasting a single object.
Merging is not only about missing keys. Three more things fall out of the same traversal:
- Unions appear where the data disagrees.
numberin one record andstringin another becomenumber | string, deduplicated by shape so a field that mixes three types does not produce five union members. - null joins the union instead of widening the whole type. One null in twenty records gives
string | null— notunknown, and not a silently dropped field. - Nesting merges at its own level. An object inside an array inside an object is merged with its own counterparts, so optionality is decided where the variation actually is, not inherited from the parent.
The practical rule: paste the largest response you can get, or several. Ten records cost nothing extra and catch almost every optional field a single record hides.
What no generator can decide for you
Even with a thousand samples, five things are inference-proof. They are not limitations of a particular tool — they are information the data does not contain.
- Literal unions. A status field that is
"shipped"in your sample is typed asstring, not'shipped' | 'pending'. The sample is one observation, not the set of allowed values — and a generator that guessed would be inventing an enum from a single row. - Dates. JSON has no date type. An ISO-8601 string is
stringand staysstring. Typing it asDatewould be a lie that only fails at runtime, when someone calls.toISOString()on a string. - Integers past 2^53. By the time the value reaches the generator it has already been through
JSON.parse, so a 19-digit ID is a double and prints back with different digits. The type isnumbereither way; the fix lives in the API, not in the types. - Optional versus nullable.
b?: numbermeans the key may be absent. It says nothing aboutb: null. Only a null in the sample justifies| null, which is why merging samples matters more than merging types. - Discriminated unions. A
paymentobject that is a card in one response and a bank transfer in another is inferred as one object with every field optional. Collapsing two variants into one loose shape is the correct inference from the data and the wrong model of the domain; splitting it by hand is a decision only you can make.
Each of these is a five-line edit after generation, and each is worth doing: generated types are a starting point that removes the mechanical work, not a finished contract.
Interfaces erase, schemas do not
There is one more decision, and unlike the six above it has nothing to do with the sample: what should exist at runtime.
A TypeScript interface is erased by the compiler. It describes what your code passes around, and it cannot inspect a response, because after compilation there is nothing left to run. That is fine for a value you produced. It is not fine for a value a server produced.
A Zod schema is a real object. schema.parse(body) either returns typed data or throws with the path that failed — items[1].unitPrice: expected number, received string. On the untrusted boundary, that error is worth more than any compile-time type, because the bug is happening right then rather than three call frames later.
The pattern that keeps both honest is to define the schema and derive the type from it with z.infer, so the validator and the types cannot drift apart. Generating the TypeScript interfaces and writing the schema by hand reintroduces exactly the duplication you were trying to remove.
Keeping the types honest after generation
- Generate from the real payload, once. Not from the docs and not from a hand-written sample. The docs describe the contract; the payload describes what the endpoint actually returns today, and those differ more often than anyone admits.
- Name the root before you copy. Nested types inherit the root name, so
OrderproducesOrderCustomerwhereRootproducesRootCustomer— the same types, with a name that tells you what they are. - Commit the file and let it diff. When the API adds a field, the regenerated file shows one added line in review. That is a change worth noticing, and a type generated at build time hides it.
- Add the literal unions by hand. Narrow the status and enum fields once, in a small file of your own that extends the generated one, so regeneration does not throw your work away.
None of this makes the types correct — it makes them honest about what they were derived from, which is the most a sample can support.