Feature: Normalize TypeScript Enum Key Names #206
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Introduction
The
@openapi-codegen/typescript
library currently generates enum keys directly from the string values of the enums. This behavior causes issues when the enum values include characters that are not allowed in TypeScript identifiers, such as spaces or hyphens.Problem
When the enum values contain characters like
, or any character not allowed in a TypeScript identifier, the generated enum keys are invalid and cause syntax errors.
-
,Solution
This update introduces a
.replace(/[^a-z0-9_]/gi, "_")
transformation in the enum key generation logic. This sanitization ensures that all generated enum keys are valid TypeScript identifiers, replacing any disallowed characters with an underscore (_
).Changes
.replace(/[^a-z0-9_]/gi, "_")
transformation for string enums.Impact
These changes will allow the
@openapi-codegen/typescript
library to handle a broader set of enum values without failing and will prevent issues with TypeScript compilation for users of the library. However, it's important to note that in scenarios where enum values only differ by characters that are sanitized into underscores (e.g.,A/B
andA:B
both becomingA_B
), this can lead to identifier collisions. Despite this, such collisions should be a rare edge case and, importantly, the previous behavior where these values resulted in invalid TypeScript identifiers meant that the generation process would fail in any case. This change ensures that generation succeeds and produces a valid TypeScript code, albeit with potential naming conflicts that can be addressed in subsequent iterations or through manual intervention in the spec if they arise.How to Test
@fabien0102 , Please review the changes and provide feedback.