DevToolBox

JSON to TypeScript Converter

JSONデータからTypeScriptのinterface/type定義を自動生成します。

// ここに結果が表示されます

How to Use the JSON to TypeScript Converter

This tool automatically generates TypeScript interface or type definitions from JSON data. Paste your JSON, click convert, and get clean TypeScript types instantly. Nested objects are extracted into separate interfaces, array element types are inferred, and property names with special characters are properly quoted. Perfect for quickly typing API responses in TypeScript projects. All processing happens in your browser.

Features

  • Nested objects become separate, named interfaces instead of one deep inline type
  • Array element types are inferred; mixed primitives produce a union like (string | number)[]
  • Keys that are not valid identifiers (user-id, 2fa) are automatically quoted
  • Switch between interface and type alias output with one checkbox
  • Custom root name, so the generated type drops straight into your codebase

Interface vs. Type Alias

For plain object shapes the two are interchangeable. Choose interface if you plan to extend the shape with extends or rely on declaration merging; choosetype if the result will be combined into unions or mapped types. This tool generates identical members either way, so you can switch later with a one-line edit.

How Type Inference Works

The converter walks the JSON value tree once: strings, numbers, booleans andnull map directly to TypeScript primitives, arrays collect the set of their element types, and each nested object is lifted into its own interface named after the property key. Because JSON carries no information about optionality or dates, those have to be reviewed by hand — see the pitfalls table below.

JSON to TypeScript Converterの使い方

JSONデータを貼り付けて「変換」ボタンを押すと、TypeScriptのinterface定義が自動生成されます。 ネストされたオブジェクトは個別のinterfaceとして抽出され、配列の要素型も自動推論します。 ルート名は自由に変更でき、「type (interfaceの代わり)」にチェックを入れると type エイリアス形式で出力されます。 API開発でレスポンスの型定義を素早く作成するのに便利です。

1. APIレスポンスの型付け

fetch で取得したレスポンスをそのまま貼り付け、生成された interface をtypes.ts に保存するのが最短の使い方です。as any でキャストする代わりにconst user: User = await res.json() と型注釈を付ければ、フィールド名のタイポを コンパイル時に検出できます。レスポンスが整形されていない場合は先にJSON Formatterで構文エラーがないか確認すると安全です。

2. Webhookペイロードの型化

Stripe や GitHub などの Webhook はペイロードが大きく、手書きで型を起こすと漏れが出がちです。 テスト送信で受け取った実ペイロードを貼り付ければ、ネストの深いオブジェクトも一括で interface 化されます。 ドキュメントに載っていないフィールドが実際には飛んできている、といった差異の発見にも役立ちます。

3. バックエンド完成前のフロント先行開発

API 仕様書のサンプル JSON から型を生成しておけば、バックエンドの実装を待たずに フロントエンドのコンポーネント開発を進められます。後で実レスポンスと食い違いがないかはJSON Diffでサンプルと実データを比較すると確認しやすくなります。

よくある落とし穴 / Common Pitfalls

JSONからの型推論は「そのサンプルに写っている形」しか分かりません。自動生成した型をそのまま信用すると 実行時エラーの原因になる典型パターンをまとめました。

Type inference only sees the shape of the sample you paste. These are the patterns where the generated types need a manual review.

落とし穴 / Pitfall原因 / Cause対処 / Fix
nullのフィールドがnull型になる
A null field is typed as null
サンプル値がたまたまnullだと本来の型が分からない
When the sample happens to be null, the real type is unknowable
実際の型に手で広げる(例: string | null
Widen by hand, e.g. string | null
オプショナル?が付かない
Optional properties are never detected
JSONには「省略されうる」という情報が存在しない
JSON carries no optionality information
複数サンプルを比較し、欠けるキーに?を手動付与
Compare multiple samples and add ? manually
配列内のオブジェクト形状が混在すると最後の要素で上書き
Mixed object shapes in an array: the last element wins
要素ごとに同名interfaceを生成するため前の形状が消える
Each element generates the same interface name, overwriting earlier shapes
全フィールドを含む代表要素で変換するか、手動でユニオン化
Convert from a representative element, or build the union by hand
ルートが配列だと先頭要素しか見ない
For a root-level array, only the first element is inspected
パフォーマンスと曖昧さ回避のため先頭要素のみ走査する仕様
By design, only parsed[0] is walked
全キーを持つ要素を先頭に置いてから変換
Move an element containing every key to the front first
日付がstringになる
Dates come out as string
JSONに日付型はなくISO 8601も単なる文字列
JSON has no date type; ISO 8601 is just a string
型はstringのまま、受信後にnew Date()で変換
Keep string and convert with new Date() after parsing
動的キーが個別プロパティに展開される
Dynamic keys are expanded into individual properties
IDをキーにした連想配列か固定キーかは機械判別できない
A map keyed by IDs is indistinguishable from fixed keys
Record<string, T>やインデックスシグネチャに書き換え
Rewrite as Record<string, T> or an index signature
空配列がunknown[]になる
Empty arrays become unknown[]
要素が無いため型を推論できない
There is no element to infer from
API仕様から実型を補う(例: string[]
Fill in the real type from the API spec, e.g. string[]

言語別コード例 / Code Examples by Language

JSONからの型生成をCIやスクリプトで自動化する場合の最小サンプル。

Minimal snippets to generate TypeScript types from JSON in scripts and CI.

Shell (quicktype CLI)

# JSONファイルからTypeScript型を生成 / Generate TS types from a JSON file
npx quicktype --lang ts --just-types --top-level User user.json -o user.ts

# APIレスポンスから直接 / Straight from an API response
curl -s https://api.example.com/user | npx quicktype --lang ts --just-types --top-level User -o user.ts

JavaScript / TypeScript (quicktype-core)

import { quicktype, InputData, jsonInputForTargetLanguage } from "quicktype-core";

const jsonInput = jsonInputForTargetLanguage("typescript");
await jsonInput.addSource({ name: "User", samples: [jsonString] });

const inputData = new InputData();
inputData.addInput(jsonInput);

const { lines } = await quicktype({
  inputData,
  lang: "typescript",
  rendererOptions: { "just-types": "true" },
});
console.log(lines.join("\n"));

Python (簡易ジェネレータ / minimal generator)

import json

def ts_type(v):
    if v is None: return "null"
    if isinstance(v, bool): return "boolean"
    if isinstance(v, (int, float)): return "number"
    if isinstance(v, str): return "string"
    if isinstance(v, list):
        kinds = sorted({ts_type(x) for x in v}) or ["unknown"]
        inner = kinds[0] if len(kinds) == 1 else "(" + " | ".join(kinds) + ")"
        return inner + "[]"
    return "object"

data = json.loads(raw)
fields = "\n".join(f"  {k}: {ts_type(v)};" for k, v in data.items())
print(f"interface Root {{\n{fields}\n}}")

TypeScript (zodで実行時検証ごと / runtime validation with zod)

import { z } from "zod";

// 生成した型を「正」とするなら、スキーマから型を導出する方が安全
// If types must match runtime data, derive them from a schema instead
const User = z.object({
  id: z.number(),
  name: z.string(),
  tags: z.array(z.string()),
});
type User = z.infer<typeof User>;

const user = User.parse(await res.json()); // 実行時にも検証される

Before / After 実例 / Before & After

例1: ネストされたJSONをinterfaceに分割 / Nested JSON into separate interfaces

{
  "id": 1,
  "name": "Aoi",
  "address": { "city": "Tokyo", "zipCode": "100-0001" }
}

interface Address {
  city: string;
  zipCode: string;
}

interface Root {
  id: number;
  name: string;
  address: Address;
}

例2: null・混在配列は生成後に手直し / Review null and mixed arrays

{ "nickname": null, "scores": [80, "N/A", 92] }

↓ 自動生成 / generated

interface Root {
  nickname: null;
  scores: (number | string)[];
}

↓ 手直し後 / after manual fix

interface Root {
  nickname: string | null;
  scores: (number | "N/A")[];
}

例3: 識別子に使えないキーは自動クォート / Invalid identifiers are quoted

{ "user-id": 42, "2fa": true }

↓ typeモード / type alias mode

type Root = {
  "user-id": number;
  "2fa": boolean;
};

ハイフン入り・数字始まりのキーはクォート必須。ドット記法ではなく obj["user-id"] でアクセスします。

Keys with hyphens or leading digits must stay quoted; access them with bracket notation.

Why browser-only? / なぜブラウザ完結か

The JSON you paste into a type generator is rarely a toy example — it is usually a real API response captured from staging or production, complete with bearer tokens, session IDs, email addresses, and internal record identifiers. Sending that payload to a server-side converter means handing your live data to a third party just to get a type definition back. DevToolBox performs the entire conversion — JSON.parse, recursive type inference, and interface generation — inside your browser with no network request at all. You can verify this yourself: open DevTools, switch to the Network tab, run a conversion, and watch the tab stay empty. The page also works offline once loaded. For typing confidential payloads from internal systems, that guarantee matters more than any feature.

型生成に貼り付けるJSONは、検証環境や本番から取得した「生のレスポンス」であることがほとんどで、 アクセストークンやメールアドレス、社内IDが含まれがちです。本ツールはパースから型推論・interface生成まで すべてブラウザ内で完結し、ネットワーク送信は一切行いません。DevTools の Network タブが空のままであることで 確認でき、一度読み込めばオフラインでも動作します。

開発をもっと効率的に

PR