-
Notifications
You must be signed in to change notification settings - Fork 132
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
Typesafe API to retrieve enums from strings #642
Comments
You should be able to create these functions yourself (playground): function isKeyof<T extends {}>(t: T, key: string): key is string & keyof T {
return key in t;
}
function getEnumValueOrDefault<T extends {}>(e: T, key: string): 0 | T[string & keyof T] {
return isKeyof(e, key) ? e[key] : 0;
} |
Yeah I agree it's possible to workaround, but I was hoping protobuf-ts could include these e.g. in the generated code of each enum so it's right on the type, rather than something we need to pull together or go find. |
The enums are just TS enums. No extra properties or methods can be added and have them be TS enums. |
Fair enough; well IMO there's room for protobuf-ts to improve the ergonomics of string->enum lookups vs. what TypeScript provides out of the box, but I understand if you disagree. |
To my knowledge, TypeScript's support for going from a string to an enum requires that the string be typed as
keyof typeof MyEnum
. This works for string literals like the example but doesn't work for arbitrary strings which could be invalid values. Here's a playground demo which reports anElement implicitly has an 'any' type
error.As a more concrete example, I am receiving a string from an untyped client that "should" be an enum value. To satisfy the type checker I need to cast the key
as
the expected type, and then handle the potentialundefined
that is returned on a miss to convert it to the enum's 0th value:It would be really useful if protobuf-ts provided a more ergonomic string-to-enum utility than what TypeScript provides. At a minimum it should support arbitrary strings without needing casting, and potentially it could behave like the protobuf spec and return the 0th enum value rather than
undefined
.The text was updated successfully, but these errors were encountered: