Skip to content

Generate as const Enum-like Objects Alongside String Unions #2366

Open
@naseemkullah

Description

@naseemkullah

Description

Hello,

openapi-typescript currently generates enums as string union types (e.g., export type Foo = 'bar' | 'baz';) when no further configuration is supplied. This is great for type-checking assignments and adheres to the OpenAPI specification.

To significantly enhance DevEx , we should generate as const enum-like objects with the same name as their corresponding string union types.

Key Benefits of this Approach:

  • Improved Autocompletion & Type Safety for Value Access: Consumers gain full IntelliSense when accessing specific enum values (e.g., Foo.bar)

  • No Breaking Change for Existing Consumers: The existing export type Foo = ... string union remains fully compatible, ensuring that current consumers' code will continue to work without modification.

  • No Naming Conflicts: TypeScript's declaration merging rules allow a const Foo and a type Foo with the same name to coexist gracefully in the same scope.

Proposal

Proposed Output Example:

// Proposed `as const` enum-like object
export const Foo = {
  bar: 'bar',
  baz: 'baz',
  qaz: 'qaz',
} as const;

// The existing string union type remains compatible
export type Foo = (typeof Foo)[keyof typeof Foo];

Extra

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestopenapi-tsRelevant to the openapi-typescript library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions