Skip to content

[FEATURE] Generate Exported Constants for Properties with const Values #2399

@frankyhun

Description

@frankyhun

Why do we need this improvement?

When defining schemas in AsyncAPI documents, the const keyword is used to enforce that a property must have a specific, fixed value. However, in the current TypeScript model generation, these fixed values are hardcoded in the interfaces, limiting reusability and clarity.

We propose that properties defined with the const keyword in the AsyncAPI schema should also generate exported constants in the TypeScript models. These constants can then be referenced in the generated interfaces, improving code maintainability and consistency.

Example Input Schema:

asyncapi: '3.0.0'
info:
  title: Example API
  version: '1.0.0'
channels:
  example/channel:
    publish:
      message:
        contentType: application/json
        payload:
          type: object
          properties:
            eventType:
              type: string
              const: "EXAMPLE_EVENT"

Expected Output in TypeScript:

// Exported constant
export const EVENT_TYPE = "EXAMPLE_EVENT";

// Interface using the constant
export interface ExampleMessage {
  eventType: typeof EVENT_TYPE; // Enforces the fixed value
}

How will this change help?

  • Improved Reusability: The constant can be reused across the codebase instead of hardcoding the value multiple times.
  • Enhanced Readability: Exported constants make the intent of fixed values more explicit.
  • Better Maintainability: If the constant value changes, it only needs to be updated in one place.
  • Alignment with TypeScript Best Practices: Encourages using constants for fixed values instead of inline literals.

Screenshots

No response

How could it be implemented/designed?

  • Modify the TypeScript template in the AsyncAPI Generator to:
  • Identify properties with the const keyword.
  • Generate an exported constant for each property with a const value.
  • Reference the exported constant in the corresponding interface.
  • This feature could optionally be configurable (e.g., via a generator flag) to provide flexibility for developers who may not require exported constants.

🚧 Breaking changes

No

👀 Have you checked for similar open issues?

  • I checked and didn't find a similar issue

🏢 Have you read the Contributing Guidelines?

Are you willing to work on this issue?

None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    To Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions