Skip to content

Commit c00f399

Browse files
committed
Export enums as const
1 parent 9821ec9 commit c00f399

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

smithy-typescript-codegen/src/main/java/software/amazon/smithy/typescript/codegen/EnumGenerator.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,11 @@
3535
* <p>We will generate the following:
3636
*
3737
* <pre>{@code
38-
* export enum TypedYesNo {
38+
* export const TypedYesNo = {
3939
* YES: "YEP",
4040
* NO: "NOPE",
41-
* }
41+
* } as const;
42+
* type TypedYesNo = typeof TypedYesNo[keyof typeof TypedYesNo];
4243
* }</pre>
4344
*
4445
* <p>Shapes that refer to this string as a member will use the following
@@ -88,21 +89,23 @@ private void generateUnnamedEnum() {
8889
// Named enums generate an actual enum type.
8990
private void generateNamedEnum() {
9091
writer.writeDocs("@public")
91-
.openBlock("export enum $L {", "}", symbol.getName(), () -> {
92+
.openBlock("export const $L = {", "} as const", symbol.getName(), () -> {
9293
// Sort the named values to ensure a stable order and sane diffs.
9394
// TODO: Should we just sort these in the trait itself?
9495
enumTrait.getValues()
9596
.stream()
9697
.sorted(Comparator.comparing(e -> e.getName().get()))
9798
.forEach(this::writeNamedEnumConstant);
9899
});
100+
writer.writeDocs("@public")
101+
.write("export type $L = typeof $L[keyof typeof $L]", symbol.getName(), symbol.getName(), symbol.getName());
99102
}
100103

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

104107
String name = body.getName().get();
105108
body.getDocumentation().ifPresent(writer::writeDocs);
106-
writer.write("$L = $S,", TypeScriptUtils.sanitizePropertyName(name), body.getValue());
109+
writer.write("$L: $S,", TypeScriptUtils.sanitizePropertyName(name), body.getValue());
107110
}
108111
}

smithy-typescript-codegen/src/test/java/software/amazon/smithy/typescript/codegen/EnumGeneratorTest.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,9 @@ public void generatesNamedEnums() {
3333
Symbol symbol = new SymbolVisitor(model, settings).toSymbol(shape);
3434
new EnumGenerator(shape, symbol, writer).run();
3535

36-
assertThat(writer.toString(), containsString("export enum Baz {"));
37-
assertThat(writer.toString(), stringContainsInOrder("BAR = \"BAR\",", "FOO = \"FOO\""));
36+
assertThat(writer.toString(), containsString("export const Baz = {"));
37+
assertThat(writer.toString(), stringContainsInOrder("BAR: \"BAR\",", "FOO: \"FOO\""));
38+
assertThat(writer.toString(), containsString("export type Baz = typeof Baz[keyof typeof Baz]"));
3839
}
3940

4041
@Test

0 commit comments

Comments
 (0)