What you're building
A lightweight schema validator β a miniature version of what Zod and Yup do. Given a schema object that describes expected field types, validate any unknown value against it and collect human-readable errors.
Requirements
type FieldType = "string" | "number" | "boolean"type Schema = Record<string, FieldType>validate(schema: Schema, data: unknown): { valid: true } | { valid: false; errors: string[] }- Returns
{ valid: true }whendatais an object and every key in the schema exists indatawith the correcttypeof. - Returns
{ valid: false, errors }listing every failing field as"field: expected <type>, got <actualType>". - If
datais not an object (or is null), return a single error"data is not an object".
- Returns
Stretch goals
- Add
"optional":prefix support so missing fields don't fail. - Support
arrayandobjectfield types recursively.
What this proves
You can reason about unknown input safely, use typeof, and produce clear
validation messages β a staple of form handling, API deserialization, and CLIs.
β‘ 40 XP
solution.tsTranspiled & run in your browser
Loading editorβ¦
Tests4 to pass
valid object passes
missing field is an error
non-object data returns single error
wrong type is flagged
Run your code to check these.