Generate TypeScript types from OpenAPI
Parse any OpenAPI 3.x specification and generate TypeScript interfaces or Zod schemas for all schemas — from a local file or a remote URL, in one command.
Installation
npm install -D snaptypeRequires Node.js 20+. ESM only.
Basic usage
By default, snaptype generates one file per schema — provide a directory as output. Use --single-file to combine everything into one file.
snaptype from-openapi <source> [options]# One file per schema — output must be a directory
snaptype from-openapi ./openapi.yaml -o ./src/types/
# All schemas in a single file
snaptype from-openapi ./openapi.yaml --single-file -o ./src/api-types.ts
# Remote spec (URL)
snaptype from-openapi https://petstore3.swagger.io/api/v3/openapi.json -o ./types/
# With Zod schemas
snaptype from-openapi ./openapi.yaml --zod -o ./src/schemas/Example
Given this OpenAPI spec fragment:
Download openapi.yamlopenapi.yaml
components:
schemas:
User:
type: object
required: [id, email]
properties:
id:
type: integer
email:
type: string
format: email
role:
type: string
enum: [admin, user, moderator]
address:
$ref: '#/components/schemas/Address'snaptype generates:
src/types/User.ts
export interface User {
id: number;
email: string;
role?: "admin" | "user" | "moderator";
address?: Address;
}With --zod:
src/schemas/User.ts
import { z } from 'zod';
export const UserSchema = z.object({
id: z.number(),
email: z.email(),
role: z.enum(["admin", "user", "moderator"]).optional(),
address: AddressSchema.optional(),
});
export type User = z.infer<typeof UserSchema>;What gets generated
| OpenAPI construct | TypeScript output |
|---|---|
Request / response body schemas | One interface per schema |
#/components/schemas/* | One interface per component |
oneOf / anyOf | TypeScript union type (A | B | C) |
allOf | Merged flat object |
enum values | String literal union ("a" | "b") |
required fields | Non-optional properties |
optional fields | prop?: Type |
Options
| Flag | Description |
|---|---|
--single-file | Output all schemas into one file instead of one file per schema |
--zod | Generate Zod schemas instead of (or alongside) TypeScript interfaces |
--ts | Also emit TypeScript when --zod is set |
-o, --output <path> | Output directory (default) or file path with --single-file |
-n, --naming <convention> | Property naming: camel (default), pascal, snake |
--readonly | Add readonly to all properties |
-c, --config <path> | Path to .snaptyperc config file |
CI/CD integration
Keep your TypeScript types in sync with your API contract by running snaptype in CI whenever the OpenAPI spec changes.
# GitHub Actions example
- name: Generate types from OpenAPI spec
run: npx snaptype from-openapi ./openapi.yaml --single-file -o src/api-types.ts
- name: Fail if types are out of date
run: git diff --exit-code src/api-types.ts