vinejs / vine

VineJS is a form data validation library for Node.js
https://vinejs.dev
MIT License
1.1k stars 21 forks source link

Question: Getting the validator type #61

Closed kevinmelo closed 5 months ago

kevinmelo commented 5 months ago

Package version

latest

Describe the bug

How i can get the type of the result of a Validator?

Let's say i have a class like this:

export default class MyClass {
   handle(req: Request) {
        const data = await MyValidator.validate(req.body)

        ///OTHER CODE
   }

   private saveSomething(data : <VALIDATOR_RESULT_TYPE>) {
      // other code
   }
}

If i need to declare the type of the data in my method saveSomething i would need to declare a new type that is exaclty the same as the result of my validator.

there is some better way than declare same types over and over?

Thanks and great work!

Reproduction repo

No response

RomainLanz commented 5 months ago

Hey @kevinmelo! 👋🏻

You have to use Infer.

import vine from '@vinejs/vine'
import type { Infer } from '@vinejs/vine/types'

const schema = vine.object({
  username: vine.string(),
  email: vine.string().email(),
  password: vine
    .string()
    .minLength(8)
    .maxLength(32)
    .confirmed()
})

type UserRegistration = Infer<typeof schema>
/**
 * {
 *   username: string
 *   email: string
 *   password: string
 * }
 */

📚 https://vinejs.dev/docs/getting_started#inferring-types-from-schema