Convert GraphQL JSON Responses to TypeScript

Use json to typescript to model GraphQL responses — generic data wrapper, errors array with locations, extensions, and per-query result shapes.

Real-World API Schemas

Detailed Explanation

GraphQL's Standard Response Envelope

Every GraphQL response — success or failure — has the same outer shape: an optional data object whose keys mirror the query, plus an optional errors array. Modeling that envelope generically lets you reuse it across every query in your app.

Example JSON

{
  "data": {
    "user": {
      "id": "u_42",
      "name": "Alice",
      "posts": [
        { "id": "p_1", "title": "Hello" }
      ]
    }
  },
  "errors": [
    {
      "message": "Field 'avatarUrl' is deprecated",
      "locations": [{ "line": 4, "column": 5 }],
      "path": ["user", "avatarUrl"],
      "extensions": { "code": "DEPRECATED" }
    }
  ]
}

Generated TypeScript

interface GraphQLLocation {
  line: number;
  column: number;
}

interface GraphQLError {
  message: string;
  locations?: GraphQLLocation[];
  path?: (string | number)[];
  extensions?: Record<string, unknown>;
}

interface GraphQLResponse<TData> {
  data?: TData;
  errors?: GraphQLError[];
  extensions?: Record<string, unknown>;
}

interface UserPost {
  id: string;
  title: string;
}

interface UserQueryData {
  user: {
    id: string;
    name: string;
    posts: UserPost[];
  };
}

type UserQueryResponse = GraphQLResponse<UserQueryData>;

Why data Is Optional

GraphQL responses can return { errors: [...] } with no data field at all (a request-level failure), or { data: { user: null }, errors: [...] } (a partial result). Model data as optional and user as nullable to capture both.

Conversion Tips

  • Generate one *QueryData interface per operation; share them via the generic GraphQLResponse<T> envelope.
  • Type path as (string | number)[] — array indices appear as numbers.
  • Treat extensions as Record<string, unknown> unless your server has a documented extension shape; cast at the call site when you read specific fields.
  • If you use code generators like graphql-codegen, this hand-written envelope is still useful for ad-hoc fetches, server-to-server calls, or stitching responses from multiple GraphQL endpoints.

Use Case

Building a small SSR proxy that forwards GraphQL queries to multiple backend services and needs a single generic response type instead of separate types per operation.

Try It — JSON to TypeScript

Open full tool