OpenAPI

Inference

We can infer the types of any OpenAPI spec using the inference helpers provided by @webroute/oas, without any code generation.

import { ParseSpec } from "@webroute/oas"
import Spec from "./openapi-spec.json"
 
type AppDef = ParseSpec<typeof Spec>;
//   ^? e.g.
//	{
// 			"GET /pets/{petId}": {
//				Query,
// 				Params,
// 				Output,
// 				...
//		 	 },
//			...
// 	}

This way our OpenAPI spec is directly transformed into TypeScript form, without any intermediary build or generation steps required.

Setup

To ensure correct type inference, we should place our OpenAPI spec into a .d.ts file:

// openapi-spec.json.d.ts
export default {
	// ...The raw JSON openAPI spec
}

This helps TypeScript infer the correct types for literal types, like { type: "object" } instead of { type: string }. It also makes our OpenAPI spec "real" source code now, which will not be bundled into JavaScript outputs.

The TypeScript team are actively discussing ways to support strongly-typed JSON import types here.

Client

We can use this alongside @webroute/client as a "headless", type-safe client

import { createTypedClient } from "@webroute/client"
 
const client = createTypedClient<AppDef>()({
	// ...config
})
 
const getPet = client("GET /pets/{petId}")
 
const pet = await getPet({
	// ...args
})

Learn more in the client docs.

On this page