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.
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
contentcan benullwhen the assistant returns onlytool_calls. Type it asstring | null, notstring.finish_reasonis sometimesnullmid-stream; widen the union accordingly.objectis a literal discriminator that lets you union ChatCompletion with embeddings and image responses later.- Treat
createdas Unix seconds (not milliseconds) — wrap it in anew 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
Related Topics
Convert Stripe Charge JSON to TypeScript Interfaces
Real-World API Schemas
Convert GitHub Repository API JSON to TypeScript
Real-World API Schemas
JSON to TypeScript Discriminated Union — Result/Error Pattern
Real-World API Schemas
Convert Slack Events API JSON to TypeScript
Real-World API Schemas
Convert GraphQL JSON Responses to TypeScript
Real-World API Schemas