A schema validator library
The problem
Build a small library that describes the shape of data as a schema and both checks unknown values at run time and produces the matching TypeScript type, in the style of popular validation libraries.
Requirements
- Schema builders for string, number, boolean, literal, array, object and optional values
- A parse function that takes unknown data and returns a Result with a typed value or a list of errors with paths such as user.address.city
- An Infer type that turns a schema into its TypeScript type with mapped and conditional types
- Tests that check both accepted and rejected values for every builder
- A README showing how a schema and its inferred type stay in step
Technologies
- TypeScript
- Generics
- Mapped types
- Conditional types
Step by step
- Define a Schema<T> interface with a parse method.
- Write the primitive builders and test them.
- Write array and object builders that combine child schemas and collect errors with paths.
- Write the Infer type and check it with assignments that must and must not compile.
- Use the library to validate a JSON file of your choice.
Expected result
A typed validation library where one schema gives both the run-time check and the static type.
How it is evaluated
- Every builder accepts valid values and rejects invalid ones with a useful path
- The inferred types match hand-written ones for the test schemas
- No any appears in the public API
- The code is split into small, generic, tested functions
Ways to improve it
- Add unions and discriminated unions to the schema builders
- Add transformations, such as turning a date string into a Date
- Publish it as a package with type declarations