Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

YPChen
YPChen

Posted on

     

Using Valibot for Recursive Schema Validation

Valibot's playground for the code demo

Recursive Type in TypeScript

TypeScript allows defining recursive types. For example, consider the followingUser interface:

interfaceUser{children?:User;email:`${string}@${string}`;password:string;}
Enter fullscreen modeExit fullscreen mode

Using Valibot for Schema Validation

What if you use a schema library, likeZod orValibot? The schema has been built on value-level, and you cannot assign the variant to its property inside the declaration.

import*asvfrom'valibot';constEmailSchema=v.string([v.minLength(1),v.email()]);constPasswordSchema=v.string([v.minLength(1),v.minLength(8)]);// const UserSchema?
Enter fullscreen modeExit fullscreen mode

Recursive Schema

Base on the Author's reply inthis issue, you can usev.lazy(() => UserSchema) and to create a type of theUserSchema as a type param to thev.BaseSchema genre as a type inference of theUserSchema:

typeUserSchemaType={children?:UserSchemaType;email:v.Input<typeofEmailSchema>;password:v.Input<typeofPasswordSchema>;}constUserSchema:v.BaseSchema<UserSchemaType>=v.object({children:v.optional(v.lazy(()=>UserSchema)),email:EmailSchema,password:PasswordSchema,});
Enter fullscreen modeExit fullscreen mode

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
lashawty profile image
Sean
  • Joined

nice

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi, I'm just a beginner of front-end development who uses Vue and React.
  • Work
    Front-end engineer
  • Joined

More fromYPChen

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp