CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-openapi-typescript

Convert OpenAPI 3.0 & 3.1 schemas to TypeScript type definitions

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

schema-transforms.mddocs/

Schema Transforms

Schema transform functions convert individual OpenAPI specification objects into TypeScript AST nodes. These modular functions handle different parts of the OpenAPI document and can be used independently for custom processing workflows.

Capabilities

Main Schema Transform

Orchestrates the transformation of a complete OpenAPI document by delegating to specialized transform functions.

/**
 * Transform an entire OpenAPI schema to TypeScript AST nodes
 * @param schema - Complete OpenAPI 3.0/3.1 document
 * @param ctx - Global transformation context with options
 * @returns Array of TypeScript AST nodes representing the complete schema
 */
function transformSchema(schema: OpenAPI3, ctx: GlobalContext): ts.Node[];

Usage Example:

import { transformSchema, astToString } from "openapi-typescript";

// Assume you have a parsed OpenAPI schema and context
const ast = transformSchema(openApiSchema, globalContext);
const output = astToString(ast);

Schema Object Transform

Converts individual JSON Schema objects to TypeScript type nodes with full support for composition, validation, and advanced features.

/**
 * Transform a Schema Object or Reference to TypeScript type
 * @param schemaObject - Schema Object or Reference Object from OpenAPI
 * @param options - Transform options with path context
 * @returns TypeScript type node representing the schema
 */
function transformSchemaObject(
  schemaObject: SchemaObject | ReferenceObject,
  options: TransformNodeOptions
): ts.TypeNode;

/**
 * Transform Schema Object with composition support (allOf, anyOf, oneOf)
 * @param schemaObject - Schema Object with composition keywords
 * @param options - Transform options with path context
 * @returns TypeScript type node handling composition
 */
function transformSchemaObjectWithComposition(
  schemaObject: SchemaObject,
  options: TransformNodeOptions
): ts.TypeNode;

Supported Schema Features:

  • All JSON Schema types (string, number, object, array, boolean, null)
  • Composition keywords (allOf, anyOf, oneOf)
  • String formats and patterns
  • Number constraints (minimum, maximum, multipleOf)
  • Array constraints (minItems, maxItems, uniqueItems)
  • Object properties and additional properties
  • Enums and const values
  • Nullable and default values
  • Discriminators for polymorphism

Usage Examples:

import { transformSchemaObject } from "openapi-typescript";

// Simple schema transform
const stringSchema = { type: "string", format: "email" };
const typeNode = transformSchemaObject(stringSchema, {
  path: "#/components/schemas/Email",
  ctx: globalContext,
  schema: openApiDocument
});

// Object schema with properties
const userSchema = {
  type: "object",
  properties: {
    id: { type: "string" },
    name: { type: "string" },
    email: { type: "string", format: "email" }
  },
  required: ["id", "name"]
};
const userType = transformSchemaObject(userSchema, options);

// Schema with composition
const compositeSchema = {
  allOf: [
    { $ref: "#/components/schemas/BaseUser" },
    {
      type: "object",
      properties: {
        role: { type: "string", enum: ["admin", "user"] }
      }
    }
  ]
};
const compositeType = transformSchemaObjectWithComposition(compositeSchema, options);

Components Object Transform

Transforms the OpenAPI Components Object containing reusable schemas, responses, parameters, and other components.

/**
 * Transform Components Object to TypeScript declarations
 * @param componentsObject - OpenAPI Components Object
 * @param ctx - Global transformation context
 * @returns Array of TypeScript nodes for all components
 */
function transformComponentsObject(
  componentsObject: ComponentsObject,
  ctx: GlobalContext
): ts.Node[];

Handles Components:

  • schemas - Reusable schema definitions
  • responses - Reusable response definitions
  • parameters - Reusable parameter definitions
  • requestBodies - Reusable request body definitions
  • headers - Reusable header definitions
  • pathItems - Reusable path item definitions

Usage Example:

import { transformComponentsObject } from "openapi-typescript";

const components = {
  schemas: {
    User: {
      type: "object",
      properties: {
        id: { type: "string" },
        name: { type: "string" }
      }
    },
    Product: {
      type: "object",
      properties: {
        id: { type: "string" },
        name: { type: "string" },
        price: { type: "number" }
      }
    }
  }
};

const componentNodes = transformComponentsObject(components, globalContext);

Paths Object Transform

Converts the OpenAPI Paths Object containing all API endpoints to TypeScript interfaces.

/**
 * Transform Paths Object to TypeScript interface
 * @param pathsObject - OpenAPI Paths Object with all endpoints
 * @param ctx - Global transformation context
 * @returns TypeScript type node representing all paths
 */
function transformPathsObject(
  pathsObject: PathsObject,
  ctx: GlobalContext
): ts.TypeNode;

Features:

  • Supports all HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Handles path parameters with template literal types
  • Processes operation parameters and request/response bodies
  • Supports operation IDs for named operations

Usage Example:

import { transformPathsObject } from "openapi-typescript";

const paths = {
  "/users": {
    get: {
      responses: {
        "200": {
          description: "List of users",
          content: {
            "application/json": {
              schema: { $ref: "#/components/schemas/User" }
            }
          }
        }
      }
    }
  },
  "/users/{id}": {
    get: {
      parameters: [
        {
          name: "id",
          in: "path",
          required: true,
          schema: { type: "string" }
        }
      ]
    }
  }
};

const pathsType = transformPathsObject(paths, globalContext);

Path Item Object Transform

Transforms individual Path Item Objects containing operations for a specific path.

/**
 * Transform Path Item Object to TypeScript type
 * @param pathItem - OpenAPI Path Item Object
 * @param options - Transform options with path context
 * @returns TypeScript type node for the path item
 */
function transformPathItemObject(
  pathItem: PathItemObject,
  options: TransformNodeOptions
): ts.TypeNode;

/**
 * HTTP method type union
 */
type Method = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";

Operation Object Transform

Transforms HTTP Operation Objects to TypeScript type elements.

/**
 * Transform Operation Object to TypeScript type elements
 * @param operationObject - OpenAPI Operation Object
 * @param options - Transform options with path context
 * @returns Array of TypeScript type elements for the operation
 */
function transformOperationObject(
  operationObject: OperationObject,
  options: TransformNodeOptions
): ts.TypeElement[];

/**
 * Inject operation objects into a top-level operations interface
 * @param operations - Map of operation ID to type elements
 * @param ctx - Global transformation context
 * @returns TypeScript interface declaration for operations
 */
function injectOperationObject(
  operations: Record<string, ts.TypeElement[]>,
  ctx: GlobalContext
): ts.InterfaceDeclaration;

Response Transform Functions

Functions for transforming response-related OpenAPI objects.

/**
 * Transform Response Object to TypeScript type
 * @param responseObject - OpenAPI Response Object
 * @param options - Transform options with path context
 * @returns TypeScript type node for the response
 */
function transformResponseObject(
  responseObject: ResponseObject,
  options: TransformNodeOptions
): ts.TypeNode;

/**
 * Transform Responses Object container to TypeScript type
 * @param responsesObject - OpenAPI Responses Object
 * @param options - Transform options with path context
 * @returns TypeScript type node for all responses
 */
function transformResponsesObject(
  responsesObject: ResponsesObject,
  options: TransformNodeOptions
): ts.TypeNode;

Request Body Transform

Transforms Request Body Objects to TypeScript types.

/**
 * Transform Request Body Object to TypeScript type
 * @param requestBodyObject - OpenAPI Request Body Object
 * @param options - Transform options with path context
 * @returns TypeScript type node for the request body
 */
function transformRequestBodyObject(
  requestBodyObject: RequestBodyObject,
  options: TransformNodeOptions
): ts.TypeNode;

Parameter Transform Functions

Functions for transforming parameter-related objects.

/**
 * Transform Parameter Object to TypeScript type
 * @param parameterObject - OpenAPI Parameter Object
 * @param options - Transform options with path context
 * @returns TypeScript type node for the parameter
 */
function transformParameterObject(
  parameterObject: ParameterObject,
  options: TransformNodeOptions
): ts.TypeNode;

/**
 * Transform array of parameters to structured type elements
 * @param parametersArray - Array of Parameter Objects or References
 * @param options - Transform options with path context
 * @returns Array of TypeScript type elements grouped by parameter location
 */
function transformParametersArray(
  parametersArray: (ParameterObject | ReferenceObject)[],
  options: TransformNodeOptions
): ts.TypeElement[];

Header and Media Type Transforms

Additional transform functions for specific OpenAPI objects.

/**
 * Transform Header Object to TypeScript type
 * @param headerObject - OpenAPI Header Object
 * @param options - Transform options with path context
 * @returns TypeScript type node for the header
 */
function transformHeaderObject(
  headerObject: HeaderObject,
  options: TransformNodeOptions
): ts.TypeNode;

/**
 * Transform Media Type Object to TypeScript type
 * @param mediaTypeObject - OpenAPI Media Type Object
 * @param options - Transform options with path context
 * @returns TypeScript type node for the media type
 */
function transformMediaTypeObject(
  mediaTypeObject: MediaTypeObject,
  options: TransformNodeOptions
): ts.TypeNode;

Webhooks Transform

Transforms OpenAPI 3.1 Webhooks Objects.

/**
 * Transform Webhooks Object to TypeScript type (OpenAPI 3.1)
 * @param webhooksObject - OpenAPI Webhooks Object
 * @param options - Global transformation context
 * @returns TypeScript type node for webhooks
 */
function transformWebhooksObject(
  webhooksObject: WebhooksObject,
  options: GlobalContext
): ts.TypeNode;

Utility Transform Functions

Additional utilities for specific transform scenarios.

/**
 * Create API paths enum when --make-paths-enum is enabled
 * @param pathsObject - OpenAPI Paths Object
 * @returns TypeScript enum declaration for all paths
 */
function makeApiPathsEnum(pathsObject: PathsObject): ts.EnumDeclaration;

/**
 * Check if schema object represents an enum type
 * @param schema - Schema object to check
 * @returns True if schema should generate enum vs type alias
 */
function isEnumSchema(schema: unknown): boolean;

/**
 * Convert component collection names to singular form
 * @param key - Component key (e.g., "schemas", "responses")
 * @returns Singular form of the key
 */
function singularizeComponentKey(key: string): string;

Usage Example:

import { makeApiPathsEnum, transformPathsObject } from "openapi-typescript";

// Generate paths enum
const pathsEnum = makeApiPathsEnum(pathsObject);

// Check if schema should be an enum
const shouldBeEnum = isEnumSchema(schemaObject);

// Convert collection key
const singular = singularizeComponentKey("schemas"); // "schema"

Install with Tessl CLI

npx tessl i tessl/npm-openapi-typescript

docs

cli-interface.md

core-conversion.md

index.md

schema-transforms.md

typescript-utilities.md

tile.json