Convert OpenAI Chat Completion JSON to TypeScript

Use json to typescript to model an OpenAI Chat Completion response. Covers choices array, finish_reason union, message roles, and token usage.

Real-World API Schemas

Detailed Explanation

Modeling a Chat Completion

OpenAI's Chat Completion response is a fixed envelope with a choices array. Each choice carries a message and a finish_reason from a closed set, plus a top-level usage block with token counts.

Example JSON

{
  "id": "chatcmpl-9abc",
  "object": "chat.completion",
  "created": 1717000000,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Sure — here is the summary..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 87,
    "completion_tokens": 142,
    "total_tokens": 229
  }
}

Generated TypeScript

type ChatRole = "system" | "user" | "assistant" | "tool";
type FinishReason = "stop" | "length" | "tool_calls" | "content_filter" | null;

interface ChatMessage {
  role: ChatRole;
  content: string | null;
}

interface ChatChoice {
  index: number;
  message: ChatMessage;
  finish_reason: FinishReason;
}

interface ChatUsage {
  prompt_tokens: number;
  completion_tokens: number;
  total_tokens: number;
}

interface ChatCompletion {
  id: string;
  object: "chat.completion";
  created: number;     // unix seconds
  model: string;
  choices: ChatChoice[];
  usage: ChatUsage;
}

Conversion Pitfalls

  • content can be null when the assistant returns only tool_calls. Type it as string | null, not string.
  • finish_reason is sometimes null mid-stream; widen the union accordingly.
  • object is a literal discriminator that lets you union ChatCompletion with embeddings and image responses later.
  • Treat created as Unix seconds (not milliseconds) — wrap it in a new Date(created * 1000) helper at the UI boundary.

The shape generated above is small enough to live in your repo without depending on the openai package, which is useful for edge runtimes where the SDK is too heavy.

Use Case

Calling the OpenAI Chat Completions endpoint from a Cloudflare Worker where bundling the official openai SDK is too costly, and you want exhaustive handling of finish_reason in the UI.

Try It — JSON to TypeScript

Open full tool