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;}
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?
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,});
Top comments(1)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse