-
Notifications
You must be signed in to change notification settings - Fork 75
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Regression: enum strings are broken in constructor of message types in 1.8.0 #752
Comments
Hey Azuka, the initializer does not accept string values for enum. I'd expect a type error in your call: const list = new ProjectServiceListRequest({sort: 'PROJECT_SORT_JOB_NUMBER'});
^ TS2322: Type string is not assignable to type ProjectSort v1.7.2 and earlier let the string value through if the type error is ignored, and they use it as is for JSON, without a runtime check. It is correct that the behavior for this usage is broken with v1.8.0, which adds an assertion. But I'm afraid it never was supported behavior. It may have worked in this specific situation, but only by accident, and you will run into undefined behavior in other places when ignoring the type error when constructing the message. We'll try to find a better solution for this use case, but going through |
@timostamm thanks. I didn't realize that was incorrect behavior. I've been using the enum string values in drop downs (because they're easier to read and troubleshoot than numbers). |
Yes, numeric enums are not ideal for this case. But you can use the names of the generated enum. For example, with this Protobuf enum (source): enum PrefixEnum {
PREFIX_ENUM_ZERO = 0;
PREFIX_ENUM_ONE = 1;
} The generated TypeScript enum is: export enum PrefixEnum {
ZERO = 0,
ONE = 1,
} TypeScript enums allow lookup from string or from number, and we can get a type for the string names with const names: keyof typeof PrefixEnum = ["ZERO", "ONE"]; There are several ways to get the string values for the array, but const names = proto3.getEnumType(PrefixEnum).values
.map(v => v.localName) as (keyof typeof PrefixEnum)[]; You can use these names to populate a drop-down. Then to set the value on the Protobuf message, you can convert the string name to the numerical value using the enum: const selectedName = names[0];
myMessage.enumField = PrefixEnum[selectedName]; |
I recently upgraded
@bufbuild/protoc-gen-es
and@bufbuild/protobuf
to 1.8.0 which seemed to break some behavior when constructing messages. Given:In both versions 1.7.2, and 1.8.0 the below works
but
fails.
I've worked around that by forcing a conversion using
proto3.getEnumType
, but this was affecting client calls using connectrpc and breaking serialization.Is this intended behavior, or was a regression introduced?
The text was updated successfully, but these errors were encountered: