package
Convert Swagger Spec to Typescript Types
npm install swagger2typesGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
A TypeScript utility that converts Swagger/OpenAPI specifications into pure TypeScript types for type-safe API route handling. The generated types are completely erased at runtime, adding zero overhead to your JavaScript bundle.
swagger2types transforms your Swagger/OpenAPI specs into a structured TypeScript interface that provides:
This is an advanced TypeScript tool that requires some understanding of:
- generates only TypeScript types. You'll need to implement your own API calling logic or use the provided helper utilities.
swagger2typesBest suited for developers who:
New to TypeScript or API clients? Consider starting with a full-featured library like swagger-typescript-api or openapi-generator before exploring this minimal approach.
Ready to proceed? Continue reading to understand how swagger2types works and see the examples for complete implementations.
npm install swagger2types# From a local file
swagger2types ./api-spec.json > generated/my-api.ts
# From a URL
swagger2types https://api.example.com/swagger.json > generated/my-api.ts
# From stdin
cat api-spec.json | swagger2types > generated/my-api.tsimport { generate } from 'swagger2types';
import { writeFileSync } from 'fs';
const spec = {
// Your Swagger/OpenAPI spec
openapi: '3.0.0',
// ... rest of spec
};
const generated = await generate(spec);
writeFileSync('./generated/my-api.ts', generated);The tool generates a Routes type that maps each API endpoint to its request and response types:
export type Routes = {
/** Get a list of users with optional pagination */
['GET /users']: {
Request: {
query?: { page?: number; limit?: number };
};
Response: User[];
};
/** Create a new post for a specific user */
['POST /users/${userId}/posts']: {
Request: {
params: { userId: string };
body: CreatePostRequest;
};
Response: Post;
};
// ... more routes
};Each route includes JSDoc comments from your OpenAPI spec's description or summary fields, plus request types with only the properties it actually uses:
params - Path parameters (e.g., ${userId})query - Query string parametersheaders - Required headersbody - Request body for POST/PUT/PATCH operationsOther generators create method-based clients (client.getUser(id)) that obscure the actual API structure. You end up hunting through documentation to figure out which method maps to GET /api/users/{userId}.
swagger2types keeps it simple: you work directly with routes as they appear in your API documentation. No abstraction layer, no guessing.
Traditional generators produce massive amounts of runtime code. For example, swagger-typescript-api generates over 1MB of TypeScript code for the GitHub API, resulting in 200KB+ of minified JavaScript that ships to users.
swagger2types generates only type definitions that disappear at compile time. Your bundle impact stays under 1KB regardless of API size - whether you have 10 endpoints or 1,000.
Real-world comparison using our vite-project example:
dist/assets/swagger2types-BkBWp9Hm.js 1.64 kB │ gzip: 0.87 kB
dist/assets/swagger-typescript-api-t86z52Ap.js 183.91 kB │ gzip: 19.89 kBChoose your own HTTP client, error handling, response processing, and integration approach. Works seamlessly with any framework (React, Vue, Angular, Express, Next.js) and module system (ESM, CJS).
Integrate gradually with existing codebases - no need to refactor everything to use a specific client library. The examples show different approaches you can adapt.
Here's the typical workflow from spec to type-safe API calls:
swagger2types https://petstore.swagger.io/v2/swagger.json > petstore-types.tsCopy the helper utilities from swagger-utils.ts and create a client:
import { clientFromFetch } from './swagger-utils.ts';
import type { Routes } from './petstore-types.ts';
export const petstore = clientFromFetch<Routes>({
baseUrl: 'https://petstore.swagger.io/v2/',
});// Full type safety with autocomplete
const pet = await petstore('GET /pet/${petId}', {
params: { petId: 1 }
});
const newPet = await petstore('POST /pet', {
body: {
name: 'Fluffy',
category: { id: 1, name: 'cats' },
status: 'available'
}
});
Working Examples:
Try it now: Interactive example on StackBlitz
swagger-typescript-api with a custom template to generate pure typesRoutes type mapping each endpoint to request/response types# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
# Test individual module systems
npm run test:esm
npm run test:cjsMIT
Contributions are welcome! Please feel free to submit issues and pull requests.
Estimated unpacked size across 66 packages.
615.7 MB+
Includes dependencies.