Skip to content
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

protovalidate-aware type generation #966

Open
haines opened this issue Aug 30, 2024 · 2 comments
Open

protovalidate-aware type generation #966

haines opened this issue Aug 30, 2024 · 2 comments

Comments

@haines
Copy link
Contributor

haines commented Aug 30, 2024

It would be really cool if the generated TypeScript types were aware of protovalidate rules.

For example

  • dropping the ? optional qualifier for message fields with required
  • dropping the undefined case for oneofs with required
  • generating Extract<> types and Omit<> types for fields with in/not_in

There are probably other rules that can be translated into type constraints (e.g. const), but those are the ones that we're making use of.

It makes the resulting code a lot easier to work with if you have strict TypeScript config because you'll get compile errors rather than runtime errors if you fail to set a required field on a message, and you don't have to deal with impossible situations like something potentially being undefined that you know can never be undefined because of the validation rules.

We're currently achieving this by doing some nasty regex-based post-processing of the generated code but I would love to stop doing that 🙈

@timostamm
Copy link
Member

Thanks for opening the issue, Andrew!

I'm not sure that the generated types should be modified by protovalidate rules. There's no guarantee that a given message has been validated before serialization, so you could easily get a runtime error when parsing a message that isn't valid.

But I've been thinking that protoc-gen-es could generate *Valid types that honor protovalidate rules, similar to JSON types. Protovalidate's validate function could act as a type guard, and pick up the *Valid type. Of course you could use the *Valid types without running validation yourself if you are certain that data is already valid.

@haines
Copy link
Contributor Author

haines commented Aug 30, 2024

Nice, that sounds good to me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants