Example result: Create TypeScript types from a JSON response
AI-generated example · Types From JSON
Updated

Create TypeScript types from a JSON response

Paste a few real API responses and this prompt writes matching TypeScript types, marking optional and nullable fields. It also adds a runtime validator so bad data is caught before it reaches the rest of your app.

text-code-json-to-types — claude — 79 words

Act as a TypeScript expert.

API response examples:
[PASTE 2 OR 3 REAL JSON RESPONSES]
Where it comes from: [e.g. a weather API]

Write TypeScript types that match the data, marking fields as optional or nullable where the examples differ. Use clear names and union types for fixed values. Then write a runtime validator with [LIBRARY, e.g. Zod] so bad data is caught at the edge of my app, and show how to use both in a fetch call.

Paste more than one response, including an error one. A single example hides which fields are optional.

Get a better result

What you will get

TypeScript types built from your real responses, with optional and nullable fields where the samples differ and union types for fixed values, plus a matching runtime validator and an example fetch call that uses both.

Why it works

Types written from one example are always wrong somewhere, so the prompt asks for two or three real responses. The differences between them are what reveal optional and null fields. Adding a runtime validator matters because TypeScript types vanish when the code runs, and only a check at the edge catches an API that changes without warning.

Common mistake

Every field is marked optional to be safe.

Fix: Ask it to mark a field optional only when one of your samples is missing it, and to list which sample that was.

Also watch for
  • Dates come through as Date objects in the types. JSON has no date type. Ask for strings in the raw type and a separate step that turns them into dates after validation.
  • The validator and the types drift apart later. Ask for the types to be inferred from the validator schema, so there is only one source to update.
Try a variation: handle a changed API

Ask what your app should do when the validator fails in production: log it, show a fallback, or reject the data.

Still not right? Reply with this

Here is an error response from the same API: [PASTE]. Add a union type that covers success and error, and update the validator.

More chat & writing prompts

See all 465 →