Inferensys

Prompt

OpenAPI Spec to TypeScript Type Definition Prompt Template

A practical prompt playbook for using OpenAPI Spec to TypeScript Type Definition Prompt Template in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

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 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.

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.

PRACTICAL GUARDRAILS

Use Case Fit

Where the OpenAPI-to-TypeScript prompt works well, where it breaks, and what inputs you must provide before running it.

01

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.

02

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.

03

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.

04

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.

05

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.

06

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.

PROMPT PLAYBOOK

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.

code
You 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: true becomes | null, absent nullable means required unless in a required array context.
  • Convert enum arrays into TypeScript string literal unions or const assertions.
  • For oneOf, anyOf, and allOf with a discriminator, generate discriminated unions with a shared discriminant property.
  • Mark properties as optional (?) when the property is not listed in the parent schema's required array.
  • Use readonly for properties marked readOnly: true in the schema.
  • For additionalProperties, generate an index signature [key: string]: ValueType.
  • Include JSDoc comments for each type and property using the description field from the schema.
  • If the schema contains $ref references to other component schemas, generate placeholder type references with a comment indicating the expected import path.
  • Do not use the any type unless the schema explicitly has no type constraint.
  • Prefer unknown over any for 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.

IMPLEMENTATION TABLE

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.

PlaceholderPurposeExampleValidation 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.

PROMPT PLAYBOOK

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.

IMPLEMENTATION TABLE

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 ElementType or FormatRequiredValidation 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 | null. Enum fields must use string literal unions.

Optionality marker

? postfix on property name

Present only when the OpenAPI schema property is not listed in required or has a default value. Absent otherwise.

JSDoc comment

string (JSDoc block)

Must include the OpenAPI description field if present. Must include @deprecated tag if the OpenAPI deprecated field is true. Must include @see tag if x-deprecation-url is present.

Discriminated union

type literal property

If the OpenAPI schema uses oneOf with a discriminator, the generated type must include a literal type property matching the discriminator mapping value.

Export statement

export interface or export type

Every generated type must be exported. If [OUTPUT_SCHEMA] specifies a namespace, wrap in declare namespace block instead.

Compilation unit

valid .ts file content

The entire output must pass tsc --noEmit with strict mode enabled and no errors. Test by writing output to a temp file and running the compiler.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when generating TypeScript types from OpenAPI specs and how to guard against it.

01

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.

02

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.

03

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.

04

$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.

05

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.

06

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.

IMPLEMENTATION TABLE

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.

CriterionPass StandardFailure SignalTest Method

Compilation Success

Output compiles with tsc --noEmit using TypeScript 5.x strict mode without errors.

Compiler errors related to syntax, undefined types, or unresolvable imports.

Automated: Pipe the generated output to a temporary .ts file and run tsc --noEmit --strict.

Schema Completeness

Every schema defined under components.schemas in [OPENAPI_SPEC] has a corresponding exported TypeScript interface or type alias.

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 (?) and nullability (| null) match the spec's required array and nullable field.

A required property is marked optional, a non-nullable property is unioned with null, or vice-versa.

Automated: Walk each schema's properties, check the required array, and validate the generated type's property signature against the resolved nullability.

Enum Literal Preservation

Every OpenAPI enum array is represented as a TypeScript union of string or numeric literal types, not a generic string or number.

An enum property is typed as string instead of 'optionA' | 'optionB'.

Automated: For each schema property with an enum field, parse the generated type and assert the property's type is a union of the exact literal values.

Discriminated Union Mapping

Every schema using oneOf or anyOf with a discriminator property is generated as a discriminated union, where the discriminator property is a literal type in each member.

A oneOf schema is generated as a simple union without a discriminator, or the discriminator property is typed as string.

Automated: Identify schemas with discriminator, locate the generated type, and verify it is a union of interfaces each with a literal-typed discriminator property.

$ref Resolution Integrity

All $ref pointers are resolved to their correct TypeScript type references. No $ref is left as a generic object or any.

A property referencing another schema via $ref is typed as any, object, or Record<string, any>.

Automated: Scan the spec for all $ref values, resolve their target schema names, and verify the generated type uses the corresponding TypeScript type name.

Round-Trip Example Validation

Every example value in the spec's component schemas is assignable to its generated TypeScript type without type errors.

A type error occurs when assigning a spec-provided example to a variable typed with the generated interface.

Automated: For each schema with an example, generate a test file that assigns the example to a const of the generated type and run tsc --noEmit.

Additional Properties Handling

Schemas with additionalProperties: false generate types without index signatures. Schemas with additionalProperties: { type: '...' } generate a compatible index signature.

A closed schema (additionalProperties: false) generates a type with [key: string]: any, or an open schema generates a type that rejects valid extra properties.

Automated: Check the spec for additionalProperties, then parse the generated type's AST to confirm the presence or absence of an index signature and its value type.

ADAPTATION OPTIONS

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.

code
Convert the following OpenAPI schema to a TypeScript type definition:

[OPENAPI_SCHEMA]

Return only the TypeScript type.

Watch for

  • nullable: true being ignored or mapped to null instead of | null
  • additionalProperties being silently dropped
  • oneOf/anyOf flattened into a single interface without discrimination
Prasad Kumkar

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.