npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

openapi-ts-json-schema

v1.3.0

Published

Generate TypeScript-first JSON schemas from OpenAPI definitions

Readme

openapi-ts-json-schema

Build Status Npm version Coveralls

Generate TypeScript-first JSON Schemas (.ts modules with as const) directly from your OpenAPI definitions — so you can use the same schema for both runtime validation and TypeScript type inference.

Why?

Keeping OpenAPI specs, runtime validators, and TypeScript types in sync is hard.

Many teams end up maintaining the same api models in different formats:

  • JSON Schema for runtime validation (Ajv, Fastify, etc.)
  • TypeScript types for static checking

openapi-ts-json-schema solves this by generating TypeScript JSON Schemas directly from your OpenAPI definitions: valid JSON schemas written as TypeScript modules, ready for runtime validation and type inference.

These schemas:

  • ✅ are 100% JSON Schema–compatible (usable with Ajv, Fastify, etc.)
  • ✅ are TypeScript-native (as const objects you can import)
  • ✅ can be used for type inference via json-schema-to-ts
  • ✅ are generated automatically from your OpenAPI spec

In short: OpenAPI spec becomes the single source of truth for both runtime validation and TypeScript typing.

Example

From this OpenAPI definition:

components:
  schemas:
    User:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
      required: [id, name]

You get this TypeScript JSON schema:

// components/schemas/User.ts
export default {
  type: 'object',
  properties: {
    id: { type: 'string' },
    name: { type: 'string' },
  },
  required: ['id', 'name'],
} as const;

Now you can use it for both runtime validation and type inference:

import Ajv from 'ajv';
import type { FromSchema } from 'json-schema-to-ts';

import userSchema from './components/schemas/User';

const ajv = new Ajv();
const validate = ajv.compile<FromSchema<typeof userSchema>>(userSchema);

const data: unknown = {};
if (validate(data)) {
  // data is now typed as { id: string; name: string }
} else {
  console.error(validate.errors);
}

How it works

Given an OpenAPI definition file, openapi-ts-json-schema:

Take a look at the Developer's notes for a few more in-depth explanations.

Installation

npm i openapi-ts-json-schema -D

Usage

Generate your TypeScript JSON schemas:

import { openapiToTsJsonSchema } from 'openapi-ts-json-schema';

const { outputPath } = await openapiToTsJsonSchema({
  openApiDocument: 'path/to/open-api-specs.yaml',
  definitionPathsToGenerateFrom: ['paths', 'components.schemas'],
});

Schemas are generated in a folder mirroring your OpenAPI layout (default: schemas-autogenerated).

Options

| Property | Type | Description | Default | | ---------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | | openApiDocument (required) | string | Path to the OpenApi file (supports yaml and json). | - | | definitionPathsToGenerateFrom (required) | string[] | OpenAPI object paths to generate schemas from (dot notation). Eg: ["components.schemas", "paths"] or ["paths./users/{id}", "paths./basket"]. | - | | refHandling | "import" \| "inline" \| "keep" | "import": generate and import $ref schemas."inline": inline $ref schemas."keep": keep $ref values. | "import" | | moduleSystem | "cjs" \| "esm" | Controls how import specifiers are written in generated artifacts. Configure this option based on whether the consuming project is using CommonJS or ECMAScript modules. | "cjs" | | idMapper | (params: { id: string }) => string | Customize generated schemas $ids and $refs values | - | | schemaPatcher | (params: { schema: JSONSchema }) => void | Dynamically patch generated JSON schemas. The provided function will be invoked against every single JSON schema node. | - | | outputPath | string | Path where the generated schemas will be saved. Defaults to /schemas-autogenerated in the same directory of openApiDocument. | - | | plugins | ReturnType<Plugin>[] | A set of optional plugins to generate extra custom output. See plugins docs. | - | | silent | boolean | Don't log user messages. | false |

$refs handling

Three strategies for how $refs are resolved:

| refHandling option | description | | -------------------- | ---------------------------------------------------------------------------------------------- | | inline | Inlines $refss, creating self-contained schemas (no imports, but possible redundancy). | | import | Replaces$refs with imports of the target definition | | keep | Leaves $refs untouched — useful if you plan to interpret $refs dynamically or use a plugin |

Circular references are supported:

  • inline: circular refs are replaced with {}
  • import: resolves the JSON schema but TypeScript recursion halts (any type, TS error 7022)
  • keep: circular refs left unresolved

See tests for details.

Return values

Along with generated schema files, openapi-ts-json-schema returns metadata:

{
  // The path where the schemas are generated
  outputPath: string;
  metaData: {
    // Meta data of the generated schemas
    schemas: Map<
      // Schema internal id. Eg: "/components/schemas/MySchema"
      string,
      {
        id: string;
        // Internal unique schema identifier. Eg `"/components/schemas/MySchema"`
        $id: string;
        // JSON schema Compound Schema Document `$id`. Eg: `"/components/schemas/MySchema"`
        uniqueName: string;
        // Unique JavaScript identifier used as import name. Eg: `"componentsSchemasMySchema"`
        openApiDefinition: OpenApiObject;
        // Original dereferenced openAPI definition
        originalSchema: JSONSchema | string;
        // Original dereferenced JSON schema
        isRef: boolean;
        // True if schemas is used as a `$ref`
        shouldBeGenerated: boolean;
        // Text content of schema file
        fileContent?: string;

        absoluteDirName: string;
        // Absolute path pointing to schema folder (posix or win32). Eg: `"Users/username/output/path/components/schemas"`
        absolutePath: string;
        // Absolute path pointing to schema file (posix or win32). Eg: `"Users/username/output/path/components/schemas/MySchema.ts"`
        absoluteImportPath: string;
        // Absolute import path (posix or win32, without extension). Eg: `"Users/username/output/path/components/schemas/MySchema"`
      }
    >;
  }
}

Plugins

Extend openapi-ts-json-schema with custom generators. Currently available plugins:

  • generateSchemaWith$idPlugin
  • fastifyIntegrationPlugin

See plugins documentation 📖.

Todo

  • Evaluate replacing definitionPathsToGenerateFrom with a more granular and flexible schema path selection strategy
  • Improve external #refs handling (currently being inlined and duplicated)
  • Find a way to merge multiple different OpenApi definitions consistently
  • Consider implementing an option to inline circular $refs with a configurable nesting level

Contributing