OpenAPI TypeScript Helpers

0.1.0 · active · verified Sun Apr 19

openapi-typescript-helpers is a utility package providing TypeScript helper types designed to complement types generated by `openapi-typescript`. Its primary purpose is to offer generic type transformations, which are internally leveraged by other packages in the `openapi-ts` ecosystem, such as `openapi-fetch`. The current stable version is `0.1.0`. Given its recent initial release and close ties to `openapi-typescript`, its release cadence is likely tied to major `openapi-typescript` releases and feature additions, though it may not have independent major version bumps as frequently. Key differentiators include its focus on type-level transformations for refining generated OpenAPI types, particularly for handling `readOnly` and `writeOnly` properties, ensuring type safety and correct data handling across different API operations. Unlike `openapi-typescript` which generates the types, this package provides tools to manipulate and refine those generated types for specific application logic.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the usage of `Readable` and `Writable` helper types to refine generated OpenAPI types for specific read and write operations, highlighting how they filter `readOnly` and `writeOnly` properties.

import type { paths } from './my-api'; // Assume this is generated by openapi-typescript
import type { Readable, Writable } from 'openapi-typescript-helpers';

// Example: Define a schema type from openapi-typescript generated types
type Pet = paths['/pets/{petId}']['get']['responses'][200]['content']['application/json'];

// Create a type for a pet when fetching (should not include writeOnly fields)
type ReadablePet = Readable<Pet>;

// Create a type for creating a pet (should not include readOnly fields)
type WritablePet = Writable<Pet>;

interface PetInput { // Simulate a type with readOnly/writeOnly markers
  id: $Read<string>;
  name: string;
  tag?: string;
  secretToken: $Write<string>;
}

type FetchablePetInput = Readable<PetInput>; // id, name, tag
type CreatablePetInput = Writable<PetInput>; // name, tag, secretToken

// You would typically use these types in your API client logic:
// async function fetchPet(petId: string): Promise<ReadablePet> { /* ... */ }
// async function createPet(newPet: WritablePet): Promise<ReadablePet> { /* ... */ }

// Demonstrate how the types change
const petToCreate: CreatablePetInput = {
  name: 'Buddy', 
  // id is excluded by Writable
  secretToken: process.env.PET_SECRET ?? '' // secretToken is included
};

const fetchedPet: FetchablePetInput = {
  id: '123',
  name: 'Buddy' 
  // secretToken is excluded by Readable
};

view raw JSON →