From ce0166e5d76bc5d55a50114bd43bfaa68dbeac18 Mon Sep 17 00:00:00 2001 From: "Marc J. Schmidt" Date: Sat, 4 May 2024 22:56:20 +0200 Subject: [PATCH] feat(type): support lower/mixed case as identifier for enum values ```typescript enum Units { MILLIGRAM = 'm', GRAM = 'g', } expect(cast('MILLIGRAM')).toBe(Units.MILLIGRAM); expect(cast('MilLiGrAm')).toBe(Units.MILLIGRAM); ``` --- packages/type/src/serializer.ts | 8 ++++++++ packages/type/tests/serializer.spec.ts | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/packages/type/src/serializer.ts b/packages/type/src/serializer.ts index e643ed878..a9e95ba9b 100644 --- a/packages/type/src/serializer.ts +++ b/packages/type/src/serializer.ts @@ -1977,7 +1977,15 @@ export class Serializer { this.serializeRegistry.register(ReflectionKind.enum, (type, state) => state.addSetter(state.accessor)); this.deserializeRegistry.register(ReflectionKind.enum, (type, state) => { const valuesVar = state.setVariable('values', type.values); + const lowercaseNames = state.setVariable('lowercaseNames', Object.keys(type.enum).map(v => v.toLowerCase())); + const allLowercased = Object.keys(type.enum).every(v => v.toLowerCase() === v); + const enumValues = state.setVariable('enumValues', type.values); + const allowLowercase = allLowercased ? '' : ` + ${state.accessor} = ${enumValues}[${lowercaseNames}.indexOf(String(${state.accessor}).toLowerCase())] ?? ${state.accessor}; + `; + state.addCodeForSetter(` + ${allowLowercase} ${state.setter} = ${state.accessor}; if (${valuesVar}.indexOf(${state.accessor}) === -1) ${state.throwCode('enum', `'No valid value of ' + ${valuesVar}.join(', ')`)} `); diff --git a/packages/type/tests/serializer.spec.ts b/packages/type/tests/serializer.spec.ts index c0787f4f2..a22c4a0f0 100644 --- a/packages/type/tests/serializer.spec.ts +++ b/packages/type/tests/serializer.spec.ts @@ -1019,6 +1019,22 @@ test('naming strategy camel case', () => { } }); +test('enum mixed case', () => { + enum Units { + MILLIGRAM = 'm', + GRAM = 'g', + KILOGRAM = 'k', + } + + expect(cast('milligram')).toBe('m'); + expect(cast('milligram')).toBe(Units.MILLIGRAM); + + expect(cast('MilliGRAM')).toBe(Units.MILLIGRAM); + + expect(cast('gram')).toBe('g'); + expect(cast('gram')).toBe(Units.GRAM); +}); + test('enum union', () => { enum StatEnginePowerUnit { Hp = 'hp',