diff --git a/src/generator.ts b/src/generator.ts index fb8d23b0..dcee32ff 100644 --- a/src/generator.ts +++ b/src/generator.ts @@ -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' + '}' ) diff --git a/test/__snapshots__/test/test.ts.md b/test/__snapshots__/test/test.ts.md index 28670fb1..0d8b981b 100644 --- a/test/__snapshots__/test/test.ts.md +++ b/test/__snapshots__/test/test.ts.md @@ -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 diff --git a/test/__snapshots__/test/test.ts.snap b/test/__snapshots__/test/test.ts.snap index 05f2ed95..79cd4741 100644 Binary files a/test/__snapshots__/test/test.ts.snap and b/test/__snapshots__/test/test.ts.snap differ diff --git a/test/e2e/enum.6.ts b/test/e2e/enum.6.ts new file mode 100644 index 00000000..5cee6fd0 --- /dev/null +++ b/test/e2e/enum.6.ts @@ -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, +}