support conditional ts enums
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
-
Prepare an OAPI schema with two kinds of enums, one with metadata and one without (see above
Status/StatusEnumexample). -
Test generating typings with the
enumflag enabled, and then toggle theconditionalEnumsto compare the differences in result.
Checklist
- [x] Unit tests updated
- [x]
docs/updated (if necessary) - [x]
pnpm run update:examplesrun (only applicable for openapi-typescript)