-
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
Get T property of FieldInfo #738
Comments
Hey Nicole, Protobuf fields can be simple scalar values, but also message references, arrays (repeated field), or records (map fields). The For example, we're walking through all fields here, and access the enum type for enum fields: for (const fi of myMessage.getType().fields.list()) {
if (fi.kind == "enum") {
const enumType: EnumType = fi.T;
}
} The TypeScript compiler narrows down the To refer to enum function findEnumFields(messageType: MessageType) {
const enumFields: (FieldInfo & {kind: "enum"})[] = [];
for (const fi of messageType.fields.list()) {
if (fi.kind == "enum") {
enumFields.push(fi);
}
}
return enumFields;
} The result is an array of We can take this one step further, to implement a function that finds an function findEnum(messageType: MessageType, fieldName: string): EnumType | undefined {
for (const fi of messageType.fields.list()) {
if (fi.localName === fieldName) {
if (fi.kind == "enum") {
return fi.T;
}
}
}
return undefined;
} Assuming you have a variable const enumType = findEnum(messageType, "myField");
if (enumType) {
enumType.values;
} Does this help? |
Thanks @timostamm , it's really useful! |
Great, I'll close this 👍 Future versions might allow this to work with type-safe field names. |
Type-safe conversion between an enum value and its JSON name is implemented in the upcoming v2 by #866. |
I am experimenting to retrieve
values
of enum FieldInfo, is there any existing API to get that? Otherwise, is it possible to exportfiPartialRules<fiScalar> | fiPartialRules<fiEnum> | fiPartialRules<fiMessage> | fiPartialRules<fiMap>
types for us? Thanks!The text was updated successfully, but these errors were encountered: