Skip to content

TypeScript

to-openapi is written in TypeScript and exports all types used in its public API. This page lists every exported type and shows common patterns for type-safe usage.

All Exported Types

The following types are exported from to-openapi:

Core API Types

TypeDescription
ToOpenapiDefinitionInput to the openapi() function
OpenAPIOptionsConstructor options for the OpenAPI class
OpenAPIDocumentThe generated OpenAPI document
RouteShorthandRoute definition (used in paths and .route())
RouteDefinitionRoute shorthand extended with method and path
HttpMethod"get" | "post" | "put" | "patch" | "delete" | "head" | "options" | "trace"

Plugin Types

TypeDescription
ToOpenapiPluginPlugin interface with transformRoute, transformSchema, and transformDocument hooks
SchemaContextContext passed to transformSchema with name and location fields
SchemaOrRefA JSON Schema object or a $ref reference object

OpenAPI Object Types

TypeDescription
InfoObjectAPI metadata (title, version, description, etc.)
ServerObjectServer URL and variables
TagObjectTag name and description
SecurityRequirementObjectSecurity requirement mapping
SecuritySchemeObjectSecurity scheme definition (apiKey, http, oauth2, openIdConnect)
PathItemObjectAll operations for a single path
OperationObjectA single API operation
ParameterObjectQuery, path, header, or cookie parameter
RequestBodyObjectRequest body with content types
ResponseObjectResponse with description and content
MediaTypeObjectMedia type with schema and examples
ComponentsObjectReusable components (schemas, security schemes, etc.)
ReferenceObjectA $ref pointer ({ $ref: string })
ExternalDocsObjectExternal documentation link

Error Types

TypeDescription
ToOpenapiErrorError class thrown by to-openapi (has code and message)
ToOpenapiErrorCode"INVALID_ROUTE_KEY" | "DUPLICATE_PATH" | "DUPLICATE_SCHEMA" | "SCHEMA_RESOLUTION_FAILED" | "INVALID_DEFINITION"

Internal Types

TypeDescription
ParsedRouteParsed route with method, path, and pathParams

HttpMethod

The HttpMethod type is a union of all HTTP methods supported by OpenAPI:

ts
import type { HttpMethod } from 'to-openapi'

const method: HttpMethod = 'get'
// Valid: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace'

ToOpenapiErrorCode

Error codes identify the category of error:

ts
import { ToOpenapiError } from 'to-openapi'
import type { ToOpenapiErrorCode } from 'to-openapi'

function handleError(err: ToOpenapiError) {
  switch (err.code) {
    case 'INVALID_ROUTE_KEY':
      // Malformed "METHOD /path" string
      break
    case 'DUPLICATE_PATH':
      // Same method + path defined twice (in merge)
      break
    case 'DUPLICATE_SCHEMA':
      // Same component schema or security scheme name (in merge)
      break
    case 'SCHEMA_RESOLUTION_FAILED':
      // Schema's jsonSchema.input() threw, or string ref not found
      break
    case 'INVALID_DEFINITION':
      // Reserved for future use
      break
  }
}

Type-Safe Route Definitions

The RouteShorthand type accepts status code keys as numeric index signatures alongside named fields:

ts
import type { RouteShorthand } from 'to-openapi'

const route: RouteShorthand = {
  summary: 'Get a user by ID',
  tags: ['users'],
  params: UserIdParamsSchema,
  200: UserSchema,
  404: null,
}

For full route definitions with method and path, use RouteDefinition:

ts
import type { RouteDefinition } from 'to-openapi'

const route: RouteDefinition = {
  method: 'get',
  path: '/users/{id}',
  summary: 'Get a user by ID',
  params: UserIdParamsSchema,
  200: UserSchema,
  404: null,
}

Type-Safe Plugin Definitions

The ToOpenapiPlugin interface defines three optional hooks:

ts
import type { ToOpenapiPlugin, SchemaContext, SchemaOrRef } from 'to-openapi'

const myPlugin: ToOpenapiPlugin = {
  name: 'my-plugin',

  transformRoute(route) {
    // Modify route definitions before processing
    return { ...route, tags: [...(route.tags ?? []), 'auto-tagged'] }
  },

  transformSchema(schema: SchemaOrRef, context: SchemaContext) {
    // Modify resolved schemas
    // context.location is 'body' | 'response'
    return schema
  },

  transformDocument(document) {
    // Modify the final assembled document
    return document
  },
}

Type-Safe OpenAPI Document

The OpenAPIDocument type represents the full OpenAPI specification:

ts
import type { OpenAPIDocument } from 'to-openapi'

function processSpec(doc: OpenAPIDocument) {
  console.log(doc.openapi)    // string ("3.1.0" or "3.0.3")
  console.log(doc.info.title) // string
  console.log(doc.paths)      // Record<string, PathItemObject>

  if (doc.components?.schemas) {
    for (const [name, schema] of Object.entries(doc.components.schemas)) {
      console.log(name, schema)
    }
  }
}