Infer Types from a Validation Schema
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Build a tiny schema library, s, with s.string(), s.number(), s.boolean(), s.array(item) and s.object(shape). Each returns a schema with parse(value), which returns the value if it matches (an object keeps only the shape's keys, an array parses every item) and throws otherwise, including for NaN, null and arrays where an object belongs. Export Infer<S>, the type a schema parses to, so the type is written once: parse returns it, nested objects and arrays included, and a shape whose values aren't schemas is a type error.
Your code must pass
- Parses valid values and drops unknown keys
- Validates arrays item by item
- Throws for values of the wrong type
- Has no type errors
- Infer gives the schema's type
- parse returns the inferred type
- Rejects a shape that isn't schemas