Skip to content

Commit

Permalink
double quote enum key if it contains special characters (#648)
Browse files Browse the repository at this point in the history
  • Loading branch information
troyshu authored Jan 14, 2025
1 parent 25c1d27 commit 18831cb
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,13 +329,20 @@ function generateComment(comment?: string, deprecated?: boolean): string {
}

function generateStandaloneEnum(ast: TEnum, options: Options): string {
const containsSpecialCharacters = (key: string): boolean => /[^a-zA-Z0-9_]/.test(key)

return (
(hasComment(ast) ? generateComment(ast.comment, ast.deprecated) + '\n' : '') +
'export ' +
(options.enableConstEnums ? 'const ' : '') +
`enum ${toSafeString(ast.standaloneName)} {` +
'\n' +
ast.params.map(({ast, keyName}) => keyName + ' = ' + generateType(ast, options)).join(',\n') +
ast.params
.map(
({ast, keyName}) =>
(containsSpecialCharacters(keyName) ? `"${keyName}"` : keyName) + ' = ' + generateType(ast, options),
)
.join(',\n') +
'\n' +
'}'
)
Expand Down
23 changes: 23 additions & 0 deletions test/__snapshots__/test/test.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -1054,6 +1054,29 @@ Generated by [AVA](https://avajs.dev).
}␊
`

## enum.6.js

> Expected output to match snapshot for e2e test: enum.6.js

`/* eslint-disable */␊
/**␊
* This file was automatically generated by json-schema-to-typescript.␊
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,␊
* and run json-schema-to-typescript to regenerate this file.␊
*/␊
export interface Enum {␊
specialStringEnum: SpecialStringEnum;␊
}␊
export const enum SpecialStringEnum {␊
"text/plain" = "text/plain",␊
a = "a",␊
"b-c" = "b-c",␊
"d.e" = "d.e"␊
}␊
`

## enum.js

> Expected output to match snapshot for e2e test: enum.js
Expand Down
Binary file modified test/__snapshots__/test/test.ts.snap
Binary file not shown.
16 changes: 16 additions & 0 deletions test/e2e/enum.6.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const input = {
title: 'Enum',
type: 'object',
properties: {
specialStringEnum: {
type: 'string',
enum: ['text/plain', 'a', 'b-c', 'd.e'],
},
},
required: ['specialStringEnum'],
additionalProperties: false,
}

export const options = {
inferStringEnumKeysFromValues: true,
}

0 comments on commit 18831cb

Please sign in to comment.