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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (1)

Collapse
 
lashawty profile image
Sean •

nice

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more