Skip to content

Commit

Permalink
Export enums as const (#726)
Browse files Browse the repository at this point in the history
* Export enums as const
  • Loading branch information
srchase authored Mar 29, 2023
1 parent 9821ec9 commit 9a52172
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@
* <p>We will generate the following:
*
* <pre>{@code
* export enum TypedYesNo {
* export const TypedYesNo = {
* YES: "YEP",
* NO: "NOPE",
* }
* } as const;
* type TypedYesNo = typeof TypedYesNo[keyof typeof TypedYesNo];
* }</pre>
*
* <p>Shapes that refer to this string as a member will use the following
Expand Down Expand Up @@ -87,22 +88,24 @@ private void generateUnnamedEnum() {

// Named enums generate an actual enum type.
private void generateNamedEnum() {
writer.writeDocs("@public")
.openBlock("export enum $L {", "}", symbol.getName(), () -> {
writer.writeDocs("@public\n@enum")
.openBlock("export const $L = {", "} as const", symbol.getName(), () -> {
// Sort the named values to ensure a stable order and sane diffs.
// TODO: Should we just sort these in the trait itself?
enumTrait.getValues()
.stream()
.sorted(Comparator.comparing(e -> e.getName().get()))
.forEach(this::writeNamedEnumConstant);
});
writer.writeDocs("@public")
.write("export type $L = typeof $L[keyof typeof $L]", symbol.getName(), symbol.getName(), symbol.getName());
}

private void writeNamedEnumConstant(EnumDefinition body) {
assert body.getName().isPresent();

String name = body.getName().get();
body.getDocumentation().ifPresent(writer::writeDocs);
writer.write("$L = $S,", TypeScriptUtils.sanitizePropertyName(name), body.getValue());
writer.write("$L: $S,", TypeScriptUtils.sanitizePropertyName(name), body.getValue());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ public void generatesNamedEnums() {
Symbol symbol = new SymbolVisitor(model, settings).toSymbol(shape);
new EnumGenerator(shape, symbol, writer).run();

assertThat(writer.toString(), containsString("export enum Baz {"));
assertThat(writer.toString(), stringContainsInOrder("BAR = \"BAR\",", "FOO = \"FOO\""));
assertThat(writer.toString(), containsString("export const Baz = {"));
assertThat(writer.toString(), stringContainsInOrder("BAR: \"BAR\",", "FOO: \"FOO\""));
assertThat(writer.toString(), containsString("export type Baz = typeof Baz[keyof typeof Baz]"));
}

@Test
Expand Down

0 comments on commit 9a52172

Please sign in to comment.