Skip to content

Commit

Permalink
feat: generate type namespaces for enums as literals (#960)
Browse files Browse the repository at this point in the history
* feat: generate type namespaces for enums as literals

* chore: amend tests to include type namespaces for enums as literals

* chore: format code
  • Loading branch information
samualtnorman authored Nov 2, 2023
1 parent 77b0555 commit e2619f6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ export const DividerData_DividerType = {

export type DividerData_DividerType = typeof DividerData_DividerType[keyof typeof DividerData_DividerType];

export namespace DividerData_DividerType {
export type DOUBLE = typeof DividerData_DividerType.DOUBLE;
export type SINGLE = typeof DividerData_DividerType.SINGLE;
export type DASHED = typeof DividerData_DividerType.DASHED;
export type DOTTED = typeof DividerData_DividerType.DOTTED;
export type UNRECOGNIZED = typeof DividerData_DividerType.UNRECOGNIZED;
}

export function dividerData_DividerTypeFromJSON(object: any): DividerData_DividerType {
switch (object) {
case 0:
Expand Down
8 changes: 8 additions & 0 deletions integration/enums-as-literals/enums-as-literals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ export const DividerData_DividerType = { DOUBLE: 0, SINGLE: 1, DASHED: 2, DOTTED

export type DividerData_DividerType = typeof DividerData_DividerType[keyof typeof DividerData_DividerType];

export namespace DividerData_DividerType {
export type DOUBLE = typeof DividerData_DividerType.DOUBLE;
export type SINGLE = typeof DividerData_DividerType.SINGLE;
export type DASHED = typeof DividerData_DividerType.DASHED;
export type DOTTED = typeof DividerData_DividerType.DOTTED;
export type UNRECOGNIZED = typeof DividerData_DividerType.UNRECOGNIZED;
}

export function dividerData_DividerTypeFromJSON(object: any): DividerData_DividerType {
switch (object) {
case 0:
Expand Down
15 changes: 15 additions & 0 deletions src/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,21 @@ export function generateEnum(
chunks.push(code`} as const`);
chunks.push(code`\n`);
chunks.push(code`export type ${def(fullName)} = typeof ${def(fullName)}[keyof typeof ${def(fullName)}]`);
chunks.push(code`\n`);
chunks.push(code`export namespace ${def(fullName)} {`);

enumDesc.value.forEach((valueDesc) => {
const memberName = getMemberName(ctx, enumDesc, valueDesc);
chunks.push(code`export type ${memberName} = typeof ${def(fullName)}.${memberName};`);
});

if (options.unrecognizedEnum && !unrecognizedEnum.present) {
chunks.push(
code`export type ${options.unrecognizedEnumName} = typeof ${def(fullName)}.${options.unrecognizedEnumName};`,
);
}

chunks.push(code`}`);
} else {
chunks.push(code`}`);
}
Expand Down

0 comments on commit e2619f6

Please sign in to comment.