Is it feasible to add a string_enums option? #288
Replies: 1 comment
-
Protobuf enums follow the same shape that exists in the generated TS enums. It's always a string key/name and an int32 value. Somewhat related to this though, I just ran into an issue where I was doing a similar thing to display a more user-friendly enum value (e.g. The problem is that after I'd created a build for my webapp (which runs the protobuf-ts codegen) someone else had modified the proto file to add a new enum value (which AFAIK is backwards compatible for protobuf purposes). Then my webapp received a message with that new enum value and it blew up with a runtime error (something like "Cannot access 'replace' on undefined"). So even though the static typing said I was okay to do something like In place of TS enums I would propose that protobuf-ts output a TS type for the enum as a string union of the proto enum keys (and importantly, // my_proto_file.proto
enum MyEnum {
FOO = 0;
BAR = 1;
} Would generate something like: // my_proto_file.ts
export type MyEnum =
| 'FOO'
| 'BAR'
| number;
// Allow runtime iteration of possible known values?
const MyEnum$KnownValues = new Set(['FOO', 'BAR'] as const);
export const MyEnumIterator = () => MyEnum$KnownValues.values(); |
Beta Was this translation helpful? Give feedback.
-
Hi again,
It seems a lot of the typescript enums are defined using string like,
enum A {
FOO = 'FOO'
}
Currently, protobuf-ts generates them with ints like,
enum A {
FOO = 0
}
I feel like this option will be very useful as it will make adopting proto in codebases were enums are string represented a lot more straightforward and light. I am currently using the 'MyEnum[val]' way to map them but requires to modify every single call site in the codebase, which is a huge undertaking.
Please let me know your thoughts.
Beta Was this translation helpful? Give feedback.
All reactions