DEV Community

YPChen
YPChen

Posted on

1

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 following User interface:

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

Using Valibot for Schema Validation

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

import * as v from 'valibot';

const EmailSchema = v.string([v.minLength(1), v.email()]);
const PasswordSchema = v.string([v.minLength(1), v.minLength(8)]);
// const UserSchema?
Enter fullscreen mode Exit fullscreen mode

Recursive Schema

Base on the Author's reply in this issue, you can use v.lazy(() => UserSchema) and to create a type of the UserSchema as a type param to the v.BaseSchema genre as a type inference of the UserSchema:

type UserSchemaType = {
 children?: UserSchemaType;
 email: v.Input<typeof EmailSchema>;
 password: v.Input<typeof PasswordSchema>;
}

const UserSchema: v.BaseSchema<UserSchemaType> = v.object({
 children: v.optional(v.lazy(() => UserSchema)),
 email: EmailSchema,
 password: PasswordSchema,
});
Enter fullscreen mode Exit fullscreen mode

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (1)

Collapse
 
lashawty profile image
Sean

nice

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay