openapi-typescript icon indicating copy to clipboard operation
openapi-typescript copied to clipboard

support conditional ts enums

Open danitt opened this issue 4 months ago • 5 comments

Changes

Adds support (via optional flag) for generating TS Enums only where there is relevant metadata.

TS Enums can provide useful mappings in specific circumstances:

enum ThingId {
  Variant1: 'f49c3b85-5cfe-473a-8ce7-f876788d211a',
  Variant2: '50f5ddfc-217c-4507-a875-165a5bbf5a41',
  Variant3: '41b85275-8018-4398-9c4f-379dbf198fc8',
}

but is also entirely redundant in many others:

enum Status {
  ok: 'ok',
  pending: 'pending',
  error: 'error',
}

This PR provides an optional --conditional-enums flag to only create TS Enums where relevant mapping metadata has been explicitly added:

components:
  schemas:
    Foo:
      type: string
      enum: [pending, active, done]
    Bar:
      type: string
      enum: [pending, active, done]
      x-enum-varnames: [Pending, Active, Done]
      x-enum-descriptions: [
        "The task is pending",
        "The task is active",
        "The task is done",
      ]

Converts to

export type Foo = 'pending' | 'active' | 'done';
export enum Bar {
  // The task is pending
  Pending: 'pending',
  // The task is active
  Active: 'active',
  // The task is done
  Done: 'done',
}

The particular use case I am targeting is for established code bases that rely 95% on simple type unions, but may occasionally wish to store enum mappings in OAPI where appropriate.

This feature would assist in cases such as https://github.com/openapi-ts/openapi-typescript/issues/941 and https://github.com/openapi-ts/openapi-typescript/issues/2366.

How to Review

  1. Prepare an OAPI schema with two kinds of enums, one with metadata and one without (see above Status / StatusEnum example).

  2. Test generating typings with the enum flag enabled, and then toggle the conditionalEnums to compare the differences in result.

Checklist

  • [x] Unit tests updated
  • [x] docs/ updated (if necessary)
  • [x] pnpm run update:examples run (only applicable for openapi-typescript)

danitt avatar Sep 08 '25 04:09 danitt