Skip to content
DevTinyTools

Typing

JSON to TypeScript: a sample is not a schema

Generating TypeScript from JSON feels like a solved problem until the second response arrives with a field missing. The interface did not change; the data did. This guide is about the gap between a type that compiles and a type that is true, and how to tell which one you have.

9 min readTool: JSON to TypeScript

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 decisions a JSON-to-TypeScript generator has to make
The situationThe choiceWhat goes wrong
A key exists in some array elements and not othersOptional, or requiredRequired 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 anotherUnion, or pick onePicking 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 nullUnion with null, or treat null as absencenull is a value, not a missing key. Collapsing it loses the distinction the API is making.
An array is empty in the sampleunknown, or invented element typeAn empty array says nothing about its elements. Guessing produces a type nobody verified.
An object appears at two different pathsOne shared type, or one per pathShared types read better but couple two unrelated shapes: change one and the other follows.
The root is an array rather than an objectType alias, or a wrapper interfaceA 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. number in one record and string in another become number | 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 — not unknown, 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 as string, 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 string and stays string. Typing it as Date would 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 is number either way; the fix lives in the API, not in the types.
  • Optional versus nullable. b?: number means the key may be absent. It says nothing about b: null. Only a null in the sample justifies | null, which is why merging samples matters more than merging types.
  • Discriminated unions. A payment object 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 Order produces OrderCustomer where Root produces RootCustomer — 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.

Frequently asked questions

Why does the same field come out differently on two machines?
Because the samples differ. Any generator describes the data it was given: paste one record and every field is required, paste five hundred records and the genuinely optional ones reveal themselves. If two people get different types, they pasted different payloads — the larger sample is the more accurate one.
Should I commit the generated file or generate on the fly?
Commit it. A generated type that lives in the repo is visible in code review and diffs when the API changes, which is exactly the signal you want. Generating at build time hides the change until something breaks.
Is it safe to paste a production response into a browser tool?
Only if the tool runs locally. This one parses and infers in the tab, with no network request — you can verify that in the network panel. Still redact tokens and personal data before pasting anything into a page you did not write.
What is the difference between interface and type here?
Nothing at runtime — both erase. Interfaces can be merged by declaration and produce clearer error messages; type aliases can express unions and mapped types. The generator writes interfaces for objects and falls back to a type alias for the root when the root is an array or a primitive.
Do I still need Zod if I have the interfaces?
If the data crosses a boundary you do not control, yes. An interface cannot reject a malformed response, because it does not exist at runtime. A schema can, and it names the path that failed. The usual pattern is to define the schema and infer the type from it, so they cannot drift.