Libraries like Zod and Joi let application code describe data shapes once and reuse them to validate values.
In this question, implement a small validator builder exposed through v. Each schema should expose safeParse(value).
This first question is intentionally limited:
v.string(), v.number(), v.boolean(), and v.object(shape).v.object(shape) only supports flat structure and all fields are required.const User = v.object({name: v.string(),age: v.number(),admin: v.boolean(),});User.safeParse({name: 'Alice',age: 30,admin: false,team: 'Core',});// {// success: true,// data: {// name: 'Alice',// age: 30,// admin: false,// team: 'Core',// },// }
Validation failures should return all top-level field errors in schema declaration order.
const User = v.object({name: v.string(),age: v.number(),admin: v.boolean(),});User.safeParse({name: 123,admin: 'yes',});// {// success: false,// errors: [// { path: ['name'], message: 'Expected string' },// { path: ['age'], message: 'Required' },// { path: ['admin'], message: 'Expected boolean' },// ],// }
v.string()Creates a schema that accepts string values. Non-string values should return Expected string.
v.number()Creates a schema that accepts number values. Non-number values should return Expected number.
v.boolean()Creates a schema that accepts boolean values. Non-boolean values should return Expected boolean.
v.object(shape)Creates a schema that validates an object against shape.
shape is an object whose values are schemas created by v.
Non-object values such as null or arrays should return Expected object.
Fields in shape are required in this question. Missing or undefined fields should return Required.
schema.safeParse(value)Returns one of the following:
{ success: true, data: value }
or
{success: false,errors: [{ path: Array<string | number>, message: string },],}
data.undefined fields should return Required.safeParse() must not mutate the input value.console.log() statements will appear here.