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;
}
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?
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,
});
Top comments (1)
nice