GraphQL → TS
Convert GraphQL SDL to TypeScript types and realistic mock data.
Runs entirely in your browser. No server calls.
How to use GraphQL → TS
Paste your SDL
Paste a GraphQL schema definition, or load one of the built-in samples.
Configure and convert
Set mock count, locale, and depth. Click Convert or press ⌘↵.
Use the output
Get TypeScript types, JSON mocks for testing, and resolver stubs ready to fill in.
Frequently asked questions
Is this free?↓
Yes, completely free. No sign-up, no rate limits.
Does my code get sent to a server?↓
No. All conversion runs entirely in your browser using JavaScript. Nothing is sent to any server.
Are all GraphQL scalar types supported?↓
Scalar types ID, String, Int, Float, Boolean, and custom scalars map to TypeScript string | number | boolean | unknown. Custom scalar types need manual overrides.
What GraphQL SDL version is supported?↓
Standard SDL (GraphQL 16.x). Directives are ignored in the output.
Try other tools
View allLong-form guide
Convert GraphQL SDL into TypeScript types and realistic mocks
GraphQL → TypeScript turns your GraphQL SDL into the three artifacts a frontend tends to need from a schema: TypeScript interfaces, realistic mock data for tests and Storybook, and resolver stubs for whoever is building the server. Paste your SDL, adjust the knobs, get usable code on the right.
How to use it
- Paste your SDL. Drop a single
type User { ... }or your whole schema. The parser uses graphql-js, so anything valid against the GraphQL 16.x spec parses cleanly. The Sample selector loads a typical blog schema if you want a reference shape. - Adjust mocks. Mocks sets how many fake objects to generate per type (1–50). Locale sets the language for fake names, addresses, and emails — Faker.js supports en, ru, and dozens more. Max depth controls how deep nested objects expand before stopping with
null. - Click Convert (or press ⌘↵). Output splits into tabs: types, mocks, resolvers. Use the tabs that match what you're building. Each tab is independently copyable and downloadable.
- Copy or download. Per-tab copy and download buttons are in the top-right of each output. The download produces a
.ts(for types and resolvers) or.json(for mocks) file with the right header.
What the generator handles
Every type, interface, and union in your SDL becomes a TypeScript interface or a discriminated union. Required fields stay required (! in SDL, no ? in TypeScript); optional fields get ?. Lists become arrays. Enums become string literal unions, with the constituent values quoted. The result is the kind of file you'd write by hand if you had a couple of free hours.
Mocks are generated by walking the schema and producing one fake object per type, repeated by your mock count. String fields with telltale names — email, firstName, lastName, city, phoneNumber, imageUrl — map to Faker.js generators that produce realistic values. ID fields become UUIDs. Numbers respect Int vs Float. Booleans are 50/50. Nested types recurse up to your max depth, then bottom out at null to avoid infinite loops on circular schemas.
Resolver stubs are typed scaffolds. Each Query, Mutation, and Subscription field becomes a function with the right argument types and return type. The body is a // TODO: implement comment, ready to be filled in. Inputs are typed against your SDL, so you can't return the wrong shape without TypeScript yelling at you.
When to reach for it
Server-first teams use it to seed a frontend before the API even has data — generate mocks, build the UI against them, swap to real data later. Frontend-first teams use it to keep types in sync with a remote schema by re-running the converter when the schema changes. QA teams use the mocks to populate test fixtures without manually crafting JSON. Designers occasionally use it to build realistic Storybook stories with believable user names instead of Lorem Ipsum.
GraphQL → TypeScript превращает GraphQL SDL в три артефакта, которые обычно нужны фронтенду от схемы: TypeScript-интерфейсы, реалистичные моки для тестов и Storybook, и заготовки резолверов для тех, кто пишет сервер. Вставь SDL, подкрути ручки — получи готовый код справа.
Как использовать
- Вставь SDL. Хоть один
type User { ... }, хоть всю схему. Парсер на graphql-js — всё валидное по спеке GraphQL 16.x парсится чисто. В Sample есть типичная блог-схема для референса. - Подкрути моки. Mocks — сколько фейк-объектов генерировать на тип (1–50). Locale — язык фейковых имён, адресов и email; Faker.js поддерживает en, ru и десятки других. Max depth — глубина раскрытия вложенных объектов до перехода в
null. - Нажми Convert (или ⌘↵). Вывод делится на вкладки: types, mocks, resolvers. Используй те, что нужны. Каждую можно отдельно копировать и скачивать.
- Скопируй или скачай. Кнопки в правом верхнем углу каждой вкладки. Скачивание даёт
.ts(типы и резолверы) или.json(моки) с правильным заголовком.
Что обрабатывает генератор
Каждый type, interface и union в твоём SDL становится TypeScript-интерфейсом или discriminated union. Required-поля остаются required (! в SDL — нет ? в TS); optional получают ?. Списки становятся массивами. Enums — string literal unions с цитированными значениями. Получаешь тот файл, который написал бы руками, будь у тебя пара свободных часов.
Моки генерируются обходом схемы — один фейк-объект на тип, повторённый столько раз, сколько ты задал. Поля строк с говорящими именами — email, firstName, lastName, city, phoneNumber, imageUrl — маппятся на генераторы Faker.js, дающие реалистичные значения. ID становятся UUID. Числа уважают Int vs Float. Boolean — 50/50. Вложенные типы рекурсируют до твоего max depth и заканчиваются null, чтобы не зацикливаться на циклических схемах.
Заготовки резолверов — типизированный скелет. Каждое поле Query, Mutation, Subscription становится функцией с правильными типами аргументов и возврата. Тело — // TODO: implement, готов к заполнению. Аргументы типизированы по твоему SDL, так что вернуть не ту форму TypeScript не даст.
Когда это пригодится
Server-first команды используют, чтобы засеять фронтенд до того, как API наполнится данными — сгенерировал моки, собрал UI на них, потом подменил на реальные. Frontend-first команды держат типы в синхроне с удалённой схемой, перезапуская конвертер при изменениях. QA-команды берут моки как фикстуры тестов без ручной верстки JSON. Дизайнеры иногда собирают реалистичные Storybook-истории с человеческими именами вместо «Lorem Ipsum».
Examples
type User {
id: ID!
email: String!
name: String
posts: [Post!]!
}
type Post {
id: ID!
title: String!
body: String!
}export interface User {
id: string;
email: string;
name?: string;
posts: Post[];
}
export interface Post {
id: string;
title: string;
body: string;
}type Author {
id: ID!
name: String!
email: String!
posts: [Post!]!
}[
{
"id": "e7e1d6f2-3b1e-4a5f-9c1f-72b8b9c2c3a1",
"name": "Maya Lindgren",
"email": "[email protected]",
"posts": []
}
]type Query {
user(id: ID!): User
}export const Query = {
user: (_: unknown, args: { id: string }): User | null => {
// TODO: implement
return null;
},
};