Skip to content

Commit ce0166e

Browse files
committed
feat(type): support lower/mixed case as identifier for enum values
```typescript enum Units { MILLIGRAM = 'm', GRAM = 'g', } expect(cast<Units>('MILLIGRAM')).toBe(Units.MILLIGRAM); expect(cast<Units>('MilLiGrAm')).toBe(Units.MILLIGRAM); ```
1 parent 0216af4 commit ce0166e

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

packages/type/src/serializer.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1977,7 +1977,15 @@ export class Serializer {
19771977
this.serializeRegistry.register(ReflectionKind.enum, (type, state) => state.addSetter(state.accessor));
19781978
this.deserializeRegistry.register(ReflectionKind.enum, (type, state) => {
19791979
const valuesVar = state.setVariable('values', type.values);
1980+
const lowercaseNames = state.setVariable('lowercaseNames', Object.keys(type.enum).map(v => v.toLowerCase()));
1981+
const allLowercased = Object.keys(type.enum).every(v => v.toLowerCase() === v);
1982+
const enumValues = state.setVariable('enumValues', type.values);
1983+
const allowLowercase = allLowercased ? '' : `
1984+
${state.accessor} = ${enumValues}[${lowercaseNames}.indexOf(String(${state.accessor}).toLowerCase())] ?? ${state.accessor};
1985+
`;
1986+
19801987
state.addCodeForSetter(`
1988+
${allowLowercase}
19811989
${state.setter} = ${state.accessor};
19821990
if (${valuesVar}.indexOf(${state.accessor}) === -1) ${state.throwCode('enum', `'No valid value of ' + ${valuesVar}.join(', ')`)}
19831991
`);

packages/type/tests/serializer.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1019,6 +1019,22 @@ test('naming strategy camel case', () => {
10191019
}
10201020
});
10211021

1022+
test('enum mixed case', () => {
1023+
enum Units {
1024+
MILLIGRAM = 'm',
1025+
GRAM = 'g',
1026+
KILOGRAM = 'k',
1027+
}
1028+
1029+
expect(cast<Units>('milligram')).toBe('m');
1030+
expect(cast<Units>('milligram')).toBe(Units.MILLIGRAM);
1031+
1032+
expect(cast<Units>('MilliGRAM')).toBe(Units.MILLIGRAM);
1033+
1034+
expect(cast<Units>('gram')).toBe('g');
1035+
expect(cast<Units>('gram')).toBe(Units.GRAM);
1036+
});
1037+
10221038
test('enum union', () => {
10231039
enum StatEnginePowerUnit {
10241040
Hp = 'hp',

0 commit comments

Comments
 (0)