DEV Community

Sanjaya Sahu
Sanjaya Sahu

Posted on

JSON to TypeScript: Stop Hand-Writing Interfaces for API Responses

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

  1. null vs optional: a field that is sometimes missing should be field?: T, one that is sometimes null is T | null.
  2. Arrays of mixed objects: merge the shapes and mark differing keys optional.
  3. Numeric strings: IDs like "123" are strings, do not convert them.
  4. 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)