JSON to TypeScript: Generating Interfaces You Can Trust

Tutorial6 min read

Hand-typing a TypeScript interface from a 40-field API response is where bugs are born. Generating the interface directly from a real sample response removes the guesswork — here's what to watch for.

1. Hand-Written Types Drift From Reality

A manually typed interface reflects what you think the API returns, not what it actually returns. Missed optional fields, wrong number/string types, and stale fields after an API update are the usual result. Generating types from a live sample keeps your interface honest.

2. Name Nested Interfaces Predictably

Deeply nested objects need a naming convention or you end up with unreadable generic names. A simple rule — name every nested interface after its parent plus the property key (UserAddress, UserAddressGeo) — keeps generated code navigable in your editor.

3. Arrays Aren't Always Simple Lists

An array of uniform objects becomes Item[]. But watch for arrays that are really fixed-length tuples (like [lat, lng] coordinate pairs) — treating those as a generic array type loses the guarantee that there are always exactly two elements.

4. Model Optional and Nullable Fields Honestly

If a field is missing on some sample objects, it should be typed optional (field?: T). If it's ever null, the type should include | null. Marking everything as required just moves the type error to runtime instead of catching it at compile time.

5. Re-generate When the API Changes

Treat generated interfaces as disposable, not hand-maintained. When an endpoint changes shape, regenerate from a fresh sample response and diff against the previous version — that diff is your changelog for what actually broke.