Hand-typing interfaces for a big API response is slow and error-prone. Generate them instead.
Why bother
Typed responses catch undefined access and renamed fields at compile time, not in production.
Pitfalls when inferring types
-
null vs optional: a field that is sometimes missing should be
field?: T, one that is sometimes null isT | null. - Arrays of mixed objects: merge the shapes and mark differing keys optional.
-
Numeric strings: IDs like
"123"are strings, do not convert them. - Sample bias: one example response never shows every variant; paste several.
Interface or type?
Use interface for object shapes you may extend, type for unions.
Validate at runtime
Types vanish at runtime. Pair them with a schema (zod) for untrusted input.
Try it
Paste JSON into the free browser-only JSON to TypeScript converter and get interfaces instantly. For runtime checks see JSON to Zod.
More tools: webdevtoolbox.com.
Top comments (0)