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

Infer the type of the req object from the schema definition #1207

Open
adamgen opened this issue Jan 26, 2023 · 1 comment
Open

Infer the type of the req object from the schema definition #1207

adamgen opened this issue Jan 26, 2023 · 1 comment

Comments

@adamgen
Copy link

adamgen commented Jan 26, 2023

Problem

Ideally when writing a schema we'd have the req type as an output. A great example of it is can be found in the zod documentation:

const Cat = z.object({ name: z.string() }).brand<"Cat">();
type Cat = z.infer<typeof Cat>;

Having that feature will be a game changer and allow more users to stay with and adopt express-validator all while enjoying first class end to end type safety.

Solution

I've made a poc in a stackblitz that allows just this for number, strings and arrays. You can see it on the link below:

https://stackblitz.com/edit/node-q8k43c?file=tests%2Findex.ts

I'd like to hear from the owners if you like that approach so I'll know if I should be working on it as a part of express-validator or as an external library.

@gustavohenke @ctavan @liqiang372 @fedeci

@gustavohenke
Copy link
Member

Hey! Yeah this is something I've been thinking of adding to express-validator.

It's a pretty hard problem to solve via schemas or not:

  • isArray/isString/isObject are pretty easy: they are literally the type that they represent;
  • custom validators can obviously implement their own type guards;
  • Most other built-in validators can't infer types as values get implicitly stringified. Sanitizers, on the other hand, can (e.g. toInt, toBoolean) -- which can be a confusing point;
  • It's been a common pain of users that sanitising arrays loses values (Sanitizing arrays loses data except first item #791), which is being fixed in v7. isArray + toInt surely means a number[], right? But what about when isArray isn't present? Both number and number[] are valid.
  • all of the above goes wild when you use negated/.not() in a chain.

With the above said, I'm definitely open to seeing a PR that implements this feature on top of #1000 (I've been actively working on it).
Whoever takes this on will likely need to work with us to find a good solution to those.

I like how you approached wildcards, the use of template literals is very smart! 😄

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

No branches or pull requests

2 participants