This prompt is designed for frontend engineers who need to generate TypeScript type definitions—interfaces, type aliases, and type guard functions—directly from OpenAPI 3.0 or 3.1 component schemas. The core job-to-be-done is eliminating manual, error-prone translation of API contracts into TypeScript types. Instead of reading a spec and typing out interfaces by hand, you provide a valid OpenAPI schema fragment, and the prompt produces compilable TypeScript that accurately reflects the source spec's nullability, enum literals, optionality, and polymorphic structures like oneOf/anyOf with discriminator fields. The ideal user is a product engineer consuming internal or external APIs who needs type safety at compile time without introducing a heavy code generation pipeline. Required context includes the raw OpenAPI component schemas (typically the #/components/schemas block) and any project-specific conventions, such as a prefix for generated type names or a preference for interface over type.
Prompt
OpenAPI Spec to TypeScript Type Definition Prompt Template

When to Use This Prompt
Understand the exact job this prompt performs, the ideal user, required inputs, and when to choose a different tool.
This prompt is scoped strictly to type-level constructs. It produces TypeScript that can be checked by tsc and used for autocompletion, parameter validation in IDEs, and compile-time safety. It does not generate runtime validation logic (e.g., Zod schemas, class-validator decorators), full API client classes with fetch wrappers, or human-readable documentation. If you need runtime request/response validation that executes in the browser or Node.js, pair this prompt's output with a schema-to-validator tool or a separate prompt designed for runtime code generation. The prompt assumes the input spec is structurally valid; it will not fix malformed $ref targets, missing type fields, or circular references that would produce nonsensical TypeScript. Pre-process your spec fragment with an OpenAPI validator before feeding it to this prompt to avoid garbage-in, garbage-out failures.
Before using this prompt, confirm that you have the exact component schemas you need—not the full spec with paths and servers unless you intend to filter them out first. If your goal is to generate types for request bodies, response objects, and parameters across all endpoints, you may need a broader code generation tool or a multi-step workflow. This prompt excels at focused schema-to-type conversion where you control exactly which schemas enter the context window. After generating the types, always run the output through tsc --noEmit and spot-check discriminated unions and enum fields against the source spec. If the output fails compilation or misrepresents a nullable field, adjust the prompt's [CONSTRAINTS] block to add explicit rules before regenerating.
Use Case Fit
Where the OpenAPI-to-TypeScript prompt works well, where it breaks, and what inputs you must provide before running it.
Good Fit: Well-Formed OpenAPI Component Schemas
Use when: your OpenAPI spec has complete components.schemas with explicit type, properties, required, nullable, and enum fields. The prompt produces accurate TypeScript interfaces and discriminated unions when the source schema is unambiguous. Guardrail: run an OpenAPI linter before feeding the spec to the prompt. Missing type fields or implicit nullability will produce incorrect TypeScript output.
Bad Fit: Handwritten or Incomplete Specs
Avoid when: the OpenAPI spec is a partial draft, uses additionalProperties: true everywhere, or omits schema definitions in favor of free-text descriptions. The prompt will hallucinate types or default to unknown. Guardrail: validate that every referenced schema has a resolved $ref target and at least one property definition before prompting.
Required Input: Resolved and Bundled Spec
What to watch: multi-file OpenAPI specs with external $ref pointers will cause the model to invent schemas for unresolved references. Guardrail: always provide a fully bundled, single-file spec with all $ref targets inlined. Use a bundler like @apidevtools/swagger-parser or redocly bundle before passing the spec to the prompt.
Operational Risk: Drift Between Spec and Live API
What to watch: the generated TypeScript types will match the spec, not the actual API responses. If the spec is stale, your frontend types will be wrong. Guardrail: add a CI step that validates live API responses against the OpenAPI spec before regenerating types. Flag any endpoint where the response body fails schema validation.
Operational Risk: Enum Literal Mismatch
What to watch: OpenAPI enum arrays with mixed types or unquoted numeric values can produce TypeScript unions that are too wide or too narrow. Guardrail: verify that every generated enum type is a string literal union unless the spec explicitly uses integer enums. Add a test that checks each enum member against the source spec array.
Operational Risk: Discriminated Union Collapse
What to watch: oneOf/anyOf schemas without a discriminator property will produce a flat union type that loses variant-specific narrowing. Guardrail: check that the spec includes a discriminator.propertyName for every polymorphic schema. If absent, the prompt should fall back to generating a tagged union with a comment warning about manual narrowing.
Copy-Ready Prompt Template
A ready-to-use prompt that generates TypeScript type definitions from an OpenAPI component schema, with placeholders for your spec, constraints, and output requirements.
This prompt template converts OpenAPI component schemas into production-ready TypeScript type definitions. It is designed for frontend engineers who need accurate interfaces, type guards, and discriminated unions that mirror the source spec exactly. The template handles nullability, enum literals, optional properties, and polymorphic structures. Before using it, ensure you have extracted the relevant schema object from your OpenAPI spec—this prompt works best with a single component schema or a focused set of related schemas, not an entire multi-thousand-line spec file dumped in at once.
codeYou are a TypeScript type definition generator. Your task is to convert an OpenAPI component schema into accurate, production-ready TypeScript type definitions. ## INPUT OpenAPI Schema: ```json [OPENAPI_SCHEMA_JSON]
Additional context about how these types will be used: [USAGE_CONTEXT]
CONSTRAINTS
- Generate only TypeScript type and interface definitions. Do not include runtime code, API clients, or fetch logic.
- Preserve exact nullability from the schema:
nullable: truebecomes| null, absent nullable means required unless in arequiredarray context. - Convert
enumarrays into TypeScript string literal unions or const assertions. - For
oneOf,anyOf, andallOfwith adiscriminator, generate discriminated unions with a shared discriminant property. - Mark properties as optional (
?) when the property is not listed in the parent schema'srequiredarray. - Use
readonlyfor properties markedreadOnly: truein the schema. - For
additionalProperties, generate an index signature[key: string]: ValueType. - Include JSDoc comments for each type and property using the
descriptionfield from the schema. - If the schema contains
$refreferences to other component schemas, generate placeholder type references with a comment indicating the expected import path. - Do not use the
anytype unless the schema explicitly has no type constraint. - Prefer
unknownoveranyfor untyped schema nodes.
OUTPUT FORMAT
Return only the TypeScript code inside a single fenced code block labeled typescript. Do not include explanations, summaries, or markdown outside the code block.
EXAMPLES
Input Schema:
json{ "type": "object", "required": ["id", "status"], "properties": { "id": { "type": "string", "description": "Unique identifier" }, "status": { "type": "string", "enum": ["active", "inactive", "pending"] }, "label": { "type": "string", "nullable": true } } }
Expected Output:
typescript/** Represents the resource. */ export interface Resource { /** Unique identifier */ id: string; status: "active" | "inactive" | "pending"; label: string | null; }
RISK_LEVEL
[RISK_LEVEL: low | medium | high]
If RISK_LEVEL is high, add a comment at the top of the output: // WARNING: Generated types for high-risk schema. Manual review required before production use.
After pasting this template, replace the square-bracket placeholders with your actual values. [OPENAPI_SCHEMA_JSON] should contain the raw JSON of a single component schema or a small set of related schemas—avoid pasting an entire spec file, as this degrades accuracy on large documents. [USAGE_CONTEXT] is optional but recommended: describe whether these types will be used in a React component, a data-fetching layer, or a shared package, as this helps the model choose appropriate export patterns and naming conventions. [RISK_LEVEL] should be set to high if the schema governs authentication, payments, PII, or compliance-sensitive data; otherwise use medium or low. For high-risk schemas, always run the generated types through a TypeScript compiler check and a manual review against the source spec before merging.
The output is a single TypeScript code block. Copy it into a .ts file and run tsc --noEmit to verify compilation. For schemas with $ref references, the model will generate placeholder imports—replace these with your actual import paths. If the schema uses oneOf with a discriminator, verify that the generated discriminated union correctly narrows on the discriminant property by writing a quick type-narrowing test. Do not ship these types without at least one round-trip check: deserialize a sample JSON response into the generated type and confirm no properties are lost or mistyped.
Prompt Variables
Required inputs for the OpenAPI-to-TypeScript prompt. Every placeholder must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of compilation failures and type drift.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[OPENAPI_SCHEMA_FRAGMENT] | The raw OpenAPI component schema or path-level request/response body to convert. Must be a valid JSON object, not a $ref pointer. | {"type":"object","properties":{"id":{"type":"integer","nullable":false}},"required":["id"]} | Parse as JSON. Reject if top-level is not an object. Reject if $ref is the only key. Warn if allOf/oneOf/anyOf are present without a discriminator. |
[SCHEMA_NAME] | The intended TypeScript interface or type alias name. Must be a valid PascalCase identifier. | UserProfileResponse | Match against /^[A-Z][a-zA-Z0-9]+$/. Reject if empty, snake_case, or contains spaces. This name will appear in the generated output. |
[NULLABLE_STRATEGY] | Controls how nullable fields are represented. Accepted values: union-null, optional, or strict. | union-null | Must be one of the three accepted enum values. union-null produces field: string | null. optional produces field?: string. strict omits the field when nullable is true and the field is not required. |
[ENUM_STYLE] | Controls how OpenAPI enum values are converted. Accepted values: union, const-assertion, or enum. | union | Must be one of the three accepted enum values. union produces type Status = 'active' | 'inactive'. const-assertion adds as const. enum produces a TypeScript enum declaration. |
[DISCRIMINATED_UNION_HINT] | Optional hint for which property acts as the discriminator when the schema uses oneOf or anyOf. Leave empty if the schema is not polymorphic. | eventType | If provided, must match a property name present in all variant schemas. If empty and the schema contains oneOf/anyOf, the model will attempt to infer the discriminator. Warn if the hint does not appear in every variant. |
[ADDITIONAL_PROPERTIES_POLICY] | Controls handling of OpenAPI additionalProperties. Accepted values: index-signature, closed, or warn-comment. | closed | Must be one of the three accepted enum values. index-signature adds [key: string]: unknown. closed omits extra properties. warn-comment adds a comment flagging that extra properties may be returned. |
[OUTPUT_FORMAT] | Specifies whether the output should be a single interface, a type guard, or both. Accepted values: interface-only, type-guard-only, or full. | full | Must be one of the three accepted enum values. full produces both the type definition and a runtime type guard function. type-guard-only still requires the schema for reference. |
Implementation Harness Notes
How to wire the OpenAPI-to-TypeScript prompt into a reliable code generation pipeline with validation, retries, and compilation checks.
This prompt is designed to be called programmatically, not used in a one-off chat. The typical harness reads an OpenAPI spec file, extracts the components.schemas block, injects it into the prompt's [OPENAPI_COMPONENT_SCHEMAS] placeholder, and sends the request to a capable code-generation model. The output is raw TypeScript that must pass through a compilation check before it ever reaches a developer's IDE. Treat the generated types as a build artifact: they should be written to a file, compiled with tsc --noEmit, and only merged into the codebase if the compilation succeeds and the type surface matches the source spec's structure.
The harness should enforce a strict validation pipeline. After the model returns, strip any markdown fences from the response and write the result to a temporary .ts file. Run tsc --noEmit --strict against it. If compilation fails, capture the error messages and feed them back into a retry prompt that includes the original schema, the failed output, and the compiler errors. Limit retries to two attempts before flagging the generation for human review. For high-stakes API surfaces, add a structural conformance check: parse the generated TypeScript AST and verify that every $ref target in the source spec has a corresponding exported type or interface, that enum values match exactly, and that nullable: true fields produce | null unions rather than optional properties.
Model choice matters here. Use a model with strong code generation performance and long-context handling if your spec is large. For specs exceeding the model's context window, split components.schemas into batches of related schemas, generate types per batch, and then run a merge pass that resolves cross-references. Log every generation attempt—input hash, model version, compilation result, and diff against the previous generated file—so you can trace regressions when the prompt or model changes. Never ship generated types without compilation and a diff review against the prior version.
Expected Output Contract
The TypeScript output must conform to this contract. Use these fields to validate generated types before integrating them into a frontend codebase.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
TypeScript interface or type alias | string (valid TS identifier) | Must start with a letter or underscore and contain only alphanumeric characters and underscores. Must not be a reserved word. | |
Property name | string (valid TS property name) | Must match the OpenAPI schema property name exactly, escaped with quotes if it contains special characters. Must be camelCase if [CONVENTIONS] specifies it. | |
Property type | string (TS type annotation) | Must map directly from the OpenAPI schema type, format, enum, or $ref. Nullable fields must include | |
Optionality marker |
| Present only when the OpenAPI schema property is not listed in | |
JSDoc comment | string (JSDoc block) | Must include the OpenAPI | |
Discriminated union |
| If the OpenAPI schema uses | |
Export statement |
| Every generated type must be exported. If [OUTPUT_SCHEMA] specifies a namespace, wrap in | |
Compilation unit | valid | The entire output must pass |
Common Failure Modes
What breaks first when generating TypeScript types from OpenAPI specs and how to guard against it.
Nullable vs Optional Confusion
What to watch: The model conflates nullable: true with required arrays, producing Type | null when the property is simply optional (Type | undefined), or vice versa. This breaks strict null checks. Guardrail: Include explicit examples in the prompt showing both nullable: true with required and optional properties without nullable. Validate output with tsc --strict.
Enum Literal Drift
What to watch: The model generates string instead of 'optionA' | 'optionB' for enum arrays, or it adds extra values not present in the spec. Guardrail: Add a constraint in the prompt to preserve exact enum literals. Post-process by extracting all enum fields from the source spec and diffing them against the generated type unions.
Discriminated Union Collapse
What to watch: For oneOf/anyOf with a discriminator, the model generates a flat union without the literal discriminant property, losing type narrowing capability. Guardrail: Explicitly instruct the model to map discriminator.propertyName to a literal type in each union member. Test by asserting that switch statements on the discriminant exhaust all cases.
$ref Resolution Failure
What to watch: The model invents inline types for $ref targets instead of generating a separate named interface, or it skips deeply nested $ref chains entirely. Guardrail: Require the model to output a flat map of all named schemas before generating the final types. Validate that every $ref in the spec has a corresponding exported type in the output.
Polymorphic Serialization Round-Trip Breakage
What to watch: Generated types compile but fail to serialize back to the original JSON structure because additionalProperties or wrapper object shapes are lost. Guardrail: Include a test harness that generates a sample object for each type, serializes it to JSON, and validates it against the source OpenAPI schema using a spec validator.
Format String Omission
What to watch: The model ignores format keywords like date-time, uri, or email, generating plain string types and losing semantic intent for validation libraries. Guardrail: Instruct the model to preserve format metadata as JSDoc @format tags or branded string types. Add a lint rule that flags any string type whose source schema had a format keyword.
Evaluation Rubric
Criteria for evaluating the quality of generated TypeScript type definitions before integrating them into a frontend codebase. Each criterion targets a specific failure mode common in spec-to-type generation.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Compilation Success | Output compiles with | Compiler errors related to syntax, undefined types, or unresolvable imports. | Automated: Pipe the generated output to a temporary |
Schema Completeness | Every schema defined under | A schema name from the spec is missing in the generated types, or a generated type has no corresponding source schema. | Automated: Parse the spec for all schema keys, parse the output for all exported type names, and compute the set difference. |
Property Nullability Accuracy | For every property, the TypeScript optionality ( | A required property is marked optional, a non-nullable property is unioned with | Automated: Walk each schema's properties, check the |
Enum Literal Preservation | Every OpenAPI | An enum property is typed as | Automated: For each schema property with an |
Discriminated Union Mapping | Every schema using | A | Automated: Identify schemas with |
| All | A property referencing another schema via | Automated: Scan the spec for all |
Round-Trip Example Validation | Every | A type error occurs when assigning a spec-provided | Automated: For each schema with an |
Additional Properties Handling | Schemas with | A closed schema ( | Automated: Check the spec for |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single OpenAPI component schema and relaxed validation. Focus on getting correct TypeScript syntax for the happy path. Skip enum literal narrowing and discriminated union handling initially.
codeConvert the following OpenAPI schema to a TypeScript type definition: [OPENAPI_SCHEMA] Return only the TypeScript type.
Watch for
nullable: truebeing ignored or mapped tonullinstead of| nulladditionalPropertiesbeing silently droppedoneOf/anyOfflattened into a single interface without discrimination

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us