Openapi To Typescript
Convert OpenAPI specifications into strongly typed TypeScript definitions automatically
Openapi To Typescript is an AI skill that automates the generation of TypeScript type definitions, API client code, and validation schemas from OpenAPI specification files. It covers schema parsing, type mapping, client generation, runtime validation, and keeping generated code synchronized with evolving API specifications.
What Is This?
Overview
Openapi To Typescript provides workflows for converting OpenAPI specification documents into strongly typed TypeScript code. It handles parsing OpenAPI 3.0 and 3.1 spec files into structured representations, mapping OpenAPI data types to TypeScript interfaces, generating API client functions with typed parameters, creating runtime validation schemas from spec constraints, watching spec files for changes and regenerating automatically, and producing discriminated union types from oneOf and anyOf constructs.
Who Should Use This
This skill serves frontend developers consuming REST APIs who want type safety, backend teams publishing API contracts for client consumption, full stack developers maintaining API specs alongside implementation, and platform teams building shared SDK libraries.
Why Use It?
Problems It Solves
Manually writing TypeScript interfaces for API responses is tedious and error prone, especially as APIs evolve. Type mismatches between client code and server responses cause runtime errors that compile time checks should prevent. Keeping client code synchronized with API changes requires manual updates across consumers.
Core Highlights
Automatic type generation eliminates manual interface writing and ensures types match the spec. Runtime validation schemas catch response format errors during development. Watch mode regenerates types when the spec file changes. Discriminated unions correctly model polymorphic response types.
How to Use It?
Basic Usage
// openapi-codegen.config.ts
import { defineConfig } from "@openapi-codegen/cli";
import {
generateSchemaTypes,
generateFetchers,
} from "@openapi-codegen/typescript";
export default defineConfig({
petStore: {
from: {
source: "file",
relativePath: "./specs/petstore.yaml",
},
outputDir: "./src/api/generated",
to: async (context) => {
const filenamePrefix = "petStore";
const { schemasFiles } = await generateSchemaTypes(
context, { filenamePrefix }
);
await generateFetchers(context, {
filenamePrefix,
schemasFiles,
});
},
},
});
// Generated usage in application code
import { getPetById } from "./api/generated/petStoreFetchers";
import type { Pet } from "./api/generated/petStoreSchemas";
async function loadPet(id: number): Promise<Pet> {
const pet = await getPetById({ pathParams: { petId: id } });
return pet;
}Real-World Examples
import { readFileSync } from "fs";
import { parse } from "yaml";
interface OpenAPISchema {
type?: string;
properties?: Record<string, OpenAPISchema>;
required?: string[];
items?: OpenAPISchema;
enum?: string[];
oneOf?: OpenAPISchema[];
}
function schemaToTypeScript(
name: string,
schema: OpenAPISchema
): string {
if (schema.enum) {
const values = schema.enum
.map((v) => `"${v}"`)
.join(" | ");
return `export type ${name} = ${values};`;
}
if (schema.type === "array" && schema.items) {
const itemType = mapType(schema.items);
return `export type ${name} = ${itemType}[];`;
}
if (schema.properties) {
const required = new Set(schema.required || []);
const fields = Object.entries(schema.properties)
.map(([key, prop]) => {
const optional = required.has(key) ? "" : "?";
return ` ${key}${optional}: ${mapType(prop)};`;
})
.join("
");
return `export interface ${name} {
${fields}
}`;
}
return `export type ${name} = ${mapType(schema)};`;
}
function mapType(schema: OpenAPISchema): string {
const typeMap: Record<string, string> = {
string: "string",
integer: "number",
number: "number",
boolean: "boolean",
};
return typeMap[schema.type || ""] || "unknown";
}Advanced Tips
Generate a barrel export file that re-exports all types from a single entry point. Use --watch during development to regenerate types as the spec evolves. Include generated code in your repository so type checking works in editors without a build step.
When to Use It?
Use Cases
Use Openapi To Typescript when building frontend applications that consume REST APIs, when publishing TypeScript SDKs for your API, when enforcing type contracts between backend and frontend teams, or when migrating JavaScript API clients to TypeScript.
Related Topics
OpenAPI specification authoring, API client libraries like Axios and Fetch, Zod schema validation, GraphQL code generation, and contract testing with Pact complement TypeScript API type generation.
Important Notes
Requirements
An OpenAPI 3.0 or 3.1 specification file in YAML or JSON format. Node.js runtime for code generation tools. A TypeScript project with strict type checking enabled.
Usage Recommendations
Do: regenerate types as part of your CI pipeline to catch spec drift early. Review generated code after major spec changes to verify discriminated unions and optional fields map correctly. Pin the code generation tool version to avoid unexpected output changes.
Don't: manually edit generated files, as changes are overwritten on the next generation run. Skip runtime validation in production, because generated types only enforce contracts at compile time. Generate clients for draft API versions without marking the generated code as experimental.
Limitations
Code generators handle common OpenAPI patterns but may produce incorrect types for deeply nested oneOf compositions or circular references. Custom format extensions like format: date-time require configuration to map to TypeScript types. Generated clients use a specific HTTP library, and switching requires changing the generator.
More Skills You Might Like
Explore similar skills to enhance your workflow
Market Segments
Identify 3-5 potential customer segments with demographics, JTBD, and product fit analysis. Use when exploring market segments, identifying target
Debugging Strategies
Transform debugging from frustrating guesswork into systematic problem-solving with proven strategies, powerful tools, and methodical approaches
Terraform Skill
Comprehensive Terraform and OpenTofu guidance covering testing, modules, CI/CD, and production patterns
Generate Custom Instructions From Codebase
generate-custom-instructions-from-codebase skill for programming & development
Golang Pro
Advanced Go development automation and integration for high-performance backend systems
Postgres Patterns
Advanced PostgreSQL design patterns for automated data modeling and high-efficiency query integration