TypeScript Tips: Types from JSON, Schema, and API Responses

By the BoltQuickTools team | April 9, 2026 | Updated November 8, 2026 | 8 min read

Writing a type by hand from an API response in the Network tab is tedious and easy to get wrong. A generated type is a faster start, but only a start, because a converter sees one sample and not the API's actual contract.

This article covers generating TypeScript types from JSON, the edge cases that need a person to check them, and how to keep types in step with the APIs they describe.

The Problem: Manual Types for API Responses

Consider a typical API response from a user endpoint:

{
  "id": 42,
  "name": "Alice Chen",
  "email": "[email protected]",
  "avatar_url": "https://cdn.example.com/avatars/42.jpg",
  "created_at": "2026-01-15T08:30:00Z",
  "settings": {
    "theme": "dark",
    "notifications": true,
    "language": "en"
  },
  "roles": ["admin", "editor"],
  "last_login": null
}

Writing the type by hand, you would produce something like this:

interface User {
  id: number;
  name: string;
  email: string;
  avatar_url: string;
  created_at: string;
  settings: {
    theme: string;
    notifications: boolean;
    language: string;
  };
  roles: string[];
  last_login: string | null;
}

That is manageable for one small object. It becomes error-prone across many endpoints or deeply nested responses.

JSON to TypeScript: Automatic Conversion

Automatic JSON-to-TypeScript conversion analyzes a JSON sample and infers the type structure. The JSON to TypeScript converter does this instantly: paste your JSON, get a TypeScript interface.

The conversion logic follows these rules:

Handling Edge Cases

Generated types get the structure right. The following cases still need a person to check them.

Nullable Fields

If a field is null in your sample, the converter only knows it can be null. It cannot infer the non-null type. You need to check the API docs or look at another response where the field is populated.

// Converter output (from a null sample)
interface User {
  last_login: null;  // Too narrow!
}

// Corrected by hand
interface User {
  last_login: string | null;  // ISO 8601 date or null
}

Optional Properties

A field that is missing from the JSON is different from a field that is null. If certain fields only appear in some responses, mark them as optional:

interface User {
  id: number;
  name: string;
  email: string;
  phone?: string;        // Not always present
  avatar_url?: string;   // Not always present
}

The converter cannot know which fields are optional from a single sample. Comparing several responses helps, and the API schema is the reliable source.

Date Strings

JSON has no date type. Dates are sent as strings, usually in ISO 8601 format. The converter types them as string, which is correct but loses meaning. A type alias documents the intent, and a branded type lets the compiler enforce it:

// Option 1: Type alias for clarity
type ISODateString = string;

interface Event {
  id: number;
  title: string;
  starts_at: ISODateString;
  ends_at: ISODateString;
}

// Option 2: Branded type for stricter checking
type ISODateString = string & { __brand: 'ISODate' };

function parseDate(iso: ISODateString): Date {
  return new Date(iso);
}

Nested Arrays of Objects

Complex responses often contain arrays of objects, which may themselves contain arrays. The converter handles this by creating separate interfaces for each nested shape:

// JSON input
{
  "orders": [
    {
      "id": 1,
      "items": [
        { "product_id": 10, "quantity": 2, "price": 29.99 }
      ]
    }
  ]
}

// TypeScript output (generated names may differ)
interface OrderItem {
  product_id: number;
  quantity: number;
  price: number;
}

interface Order {
  id: number;
  items: OrderItem[];
}

interface Root {
  orders: Order[];
}

You can format your JSON with the JSON Formatter before conversion to make the structure easier to verify visually.

JSON Schema to Types

If the API provides a JSON Schema definition (many OpenAPI/Swagger APIs do), you can generate types from the schema rather than from sample data. This is more reliable because the schema defines the full contract, including optional fields, nullable types, enums, and validation constraints.

// JSON Schema (Draft 7)
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "id": { "type": "integer" },
    "status": {
      "type": "string",
      "enum": ["active", "inactive", "suspended"]
    },
    "metadata": {
      "oneOf": [
        { "type": "object", "properties": { "source": { "type": "string" } } },
        { "type": "null" }
      ]
    }
  },
  "required": ["id", "status"]
}

// Generated TypeScript
interface Root {
  id: number;
  status: 'active' | 'inactive' | 'suspended';
  metadata?: { source?: string } | null;
}

The Schema to Code generator handles common JSON Schema Draft 7 and 2020-12 features, including local $ref resolution, oneOf/anyOf as union types, enum as literal unions, and required versus optional properties.

For validating your schema before generating types, the JSON Schema Validator will catch structural errors.

Real Workflow: From API to Types

A workflow for integrating a new API:

  1. Hit the endpoint. Use cURL or the API tester to get a real response.
  2. Format the JSON. Paste it into the JSON Formatter to see the full structure clearly.
  3. Generate the base type. Paste the formatted JSON into the JSON to TypeScript converter.
  4. Refine the type. Add optionality, fix nullables, add branded types for dates and IDs.
  5. Check against schema. If the API has a JSON Schema or OpenAPI spec, cross-reference your type to catch missing fields.
  6. Add a type guard. Write a runtime check for the most critical types.

Type Narrowing and Type Guards

Generated types are compile-time only. At runtime, the data from an API could be anything. Type guards bridge this gap:

interface User {
  id: number;
  name: string;
  email: string;
}

// Type guard function
function isUser(data: unknown): data is User {
  return (
    typeof data === 'object' &&
    data !== null &&
    typeof (data as User).id === 'number' &&
    typeof (data as User).name === 'string' &&
    typeof (data as User).email === 'string'
  );
}

// Usage
const response = await fetch('/api/user/42');
const data: unknown = await response.json();

if (isUser(data)) {
  // TypeScript knows data is User here
  console.log(data.name);
} else {
  throw new Error('Unexpected API response shape');
}

Writing type guards by hand is verbose. For complex types, runtime validation libraries are a better fit (more on that below).

Utility Types

TypeScript ships with utility types for deriving new types from existing ones, which is useful for request and response shapes that overlap.

interface User {
  id: number;
  name: string;
  email: string;
  avatar_url: string;
  created_at: string;
}

// Partial: all properties become optional
// Useful for PATCH/update requests
type UserUpdate = Partial<User>;
// { id?: number; name?: string; email?: string; ... }

// Required: all properties become required
type StrictUser = Required<User>;

// Pick: select specific properties
// Useful for list views that show less data
type UserSummary = Pick<User, 'id' | 'name' | 'avatar_url'>;
// { id: number; name: string; avatar_url: string }

// Omit: exclude specific properties
// Useful for create requests (server assigns id)
type CreateUserPayload = Omit<User, 'id' | 'created_at'>;
// { name: string; email: string; avatar_url: string }

// Record: typed key-value maps
type UserPermissions = Record<string, boolean>;
// { [key: string]: boolean }

// Combining utility types
type UserFormData = Partial<Omit<User, 'id' | 'created_at'>>;
// All editable fields, all optional

Zod and Runtime Validation

Zod is a schema validation library for TypeScript. You define a schema once and get both a runtime validator and an inferred type. This example uses Zod 4 syntax; Zod 3 used forms like z.string().email():

import { z } from 'zod';

// Define the schema (this IS your runtime validator)
const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.email(),
  avatar_url: z.url().optional(),
  created_at: z.iso.datetime(),
  roles: z.array(z.enum(['admin', 'editor', 'viewer'])),
  last_login: z.iso.datetime().nullable(),
});

// Infer the TypeScript type from the schema
type User = z.infer<typeof UserSchema>;
// No need to write the type separately!

// Runtime validation
const response = await fetch('/api/user/42');
const json = await response.json();

const user = UserSchema.parse(json);
// Throws ZodError if shape doesn't match
// Otherwise, user is typed as User

// Safe parsing (doesn't throw)
const result = UserSchema.safeParse(json);
if (result.success) {
  console.log(result.data.name); // typed as User
} else {
  console.error(result.error.issues);
}

The schema becomes the single source of truth, so types and validation cannot drift apart. In full-stack TypeScript projects the same schema can validate requests on the server and responses on the client.

Best Practices for API Type Safety

  1. Never use any for API responses. At minimum, type them as unknown and narrow from there.
  2. Centralize your API types. Keep all generated types in a single types/api.ts file or a types/ directory. This makes it easy to regenerate when the API changes.
  3. Version your types. If the API is versioned, your types should be too. UserV1 and UserV2 can coexist during migrations.
  4. Use Omit and Pick to derive request types from response types, rather than defining them separately. This ensures consistency.
  5. Add runtime validation at the boundary. The fetch call is the boundary between trusted (your code) and untrusted (the network). Validate there.
  6. Automate regeneration. If the API has an OpenAPI spec, set up a script to regenerate types on each release. Manual sync will always fall behind.

Good API types catch mistakes at compile time and give your editor accurate autocompletion. The JSON to TypeScript converter handles quick conversions, the Schema to Code generator works from formal schemas, and the JSON Schema Validator checks the schemas themselves.