Skip to content

Commit 18831cb

Browse files
authored
double quote enum key if it contains special characters (#648)
1 parent 25c1d27 commit 18831cb

File tree

4 files changed

+47
-1
lines changed

4 files changed

+47
-1
lines changed

src/generator.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,13 +329,20 @@ function generateComment(comment?: string, deprecated?: boolean): string {
329329
}
330330

331331
function generateStandaloneEnum(ast: TEnum, options: Options): string {
332+
const containsSpecialCharacters = (key: string): boolean => /[^a-zA-Z0-9_]/.test(key)
333+
332334
return (
333335
(hasComment(ast) ? generateComment(ast.comment, ast.deprecated) + '\n' : '') +
334336
'export ' +
335337
(options.enableConstEnums ? 'const ' : '') +
336338
`enum ${toSafeString(ast.standaloneName)} {` +
337339
'\n' +
338-
ast.params.map(({ast, keyName}) => keyName + ' = ' + generateType(ast, options)).join(',\n') +
340+
ast.params
341+
.map(
342+
({ast, keyName}) =>
343+
(containsSpecialCharacters(keyName) ? `"${keyName}"` : keyName) + ' = ' + generateType(ast, options),
344+
)
345+
.join(',\n') +
339346
'\n' +
340347
'}'
341348
)

test/__snapshots__/test/test.ts.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1054,6 +1054,29 @@ Generated by [AVA](https://avajs.dev).
10541054
}␊
10551055
`
10561056

1057+
## enum.6.js
1058+
1059+
> Expected output to match snapshot for e2e test: enum.6.js
1060+
1061+
`/* eslint-disable */␊
1062+
/**␊
1063+
* This file was automatically generated by json-schema-to-typescript.␊
1064+
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,␊
1065+
* and run json-schema-to-typescript to regenerate this file.␊
1066+
*/␊
1067+
1068+
export interface Enum {␊
1069+
specialStringEnum: SpecialStringEnum;␊
1070+
}␊
1071+
1072+
export const enum SpecialStringEnum {␊
1073+
"text/plain" = "text/plain",␊
1074+
a = "a",␊
1075+
"b-c" = "b-c",␊
1076+
"d.e" = "d.e"␊
1077+
}␊
1078+
`
1079+
10571080
## enum.js
10581081

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

test/__snapshots__/test/test.ts.snap

69 Bytes
Binary file not shown.

test/e2e/enum.6.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export const input = {
2+
title: 'Enum',
3+
type: 'object',
4+
properties: {
5+
specialStringEnum: {
6+
type: 'string',
7+
enum: ['text/plain', 'a', 'b-c', 'd.e'],
8+
},
9+
},
10+
required: ['specialStringEnum'],
11+
additionalProperties: false,
12+
}
13+
14+
export const options = {
15+
inferStringEnumKeysFromValues: true,
16+
}

0 commit comments

Comments
 (0)