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

Question: How to allow optional fields to be omitted? #35

Open
CodingDive opened this issue Feb 15, 2024 · 3 comments
Open

Question: How to allow optional fields to be omitted? #35

CodingDive opened this issue Feb 15, 2024 · 3 comments

Comments

@CodingDive
Copy link

CodingDive commented Feb 15, 2024

Package version

Latest (1.7.1)

Describe the bug

Thank you for this fantastic library and all the work in Adonis v6! ❤️

I tried to follow https://vinejs.dev/docs/schema_101#nullable-and-optional-modifiers

export const updateUserValidator = vine.compile(
  vine.object({
    password: vine.string().minLength(9).nullable().optional(),
  })

however, when I extract the type out of the validator:

type UpdateUser: Awaited<ReturnType<typeof updateUserValidator.validate>> I can see that the resulting type is password: string | null | undefined;. Is there a way to make it password?: string | null | undefined?

I could write a TypeScript helper to accomplish this in user land but it's not that pretty and I was wondering if there is an easier way.

type MakeUndefinedPropertiesOptional<T> = {
  [P in keyof T]-?: undefined extends T[P] ? P : never
}[keyof T] extends infer D
  ? { [P in keyof T as P extends D ? P : never]?: T[P] } & {
      [P in keyof T as P extends D ? never : P]: T[P]
    }
  : never

type UndefinedBar = { foo: string | null; bar: string | undefined; test: string }

type OptionalBar = MakeUndefinedPropertiesOptional<UndefinedBar> // { bar?: string | undefined } & { test: string; foo: string | null }

Small aside: In the repo, when clicking on "Get Help => Open", a new tab opens but it doesn't fill out the issue template with Question.

image

@RomainLanz
Copy link
Member

Hey @CodingDive! 👋🏻

That's not how you should extract the type from the validator; you should 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>

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

@CodingDive
Copy link
Author

This simplifies the code quite a bit 😅 Thank you!

I'd still need the MakeUndefinedPropertiesOptional helper as far as I can tell

@mdsadiqueinam
Copy link

how can we make all the field optional in vine object

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

3 participants