This guide shows you how to use Valibot to generate JSON Schema and then generate TypeScript types from it.
- 🔍 Use the
valibotschemas in your runtime to validate data. Seeschemas.tsfor examples. - 🔧 Automatically generate TypeScript types from the schemas.
- 🙈 Minimal code and no runtime code is generated.
- 📝 Generate JSON schemas that can be used by other tools.
- 🎉 Easy to update the code across the project.
This repo contains an example project that uses this approach.
pnpm install
pnpm run generate # Creates TypeScript types in the `types` folder- Create Valibot schemas in your application to validate data.
- You can use these schemas in your runtime to validates the data.
- See
schemas.tsfor more details.
- Copy the
./scripts/generate-typescript.tsfile to your project and modify it to your needs- You nee to update it with the schemas you want to generate types for.
- You can change the paths to the schemas and the output folder.
- Install the required packages in
devDependencies:npm i -D @types/node @valibot/to-json-schema json-schema-to-typescript pathe typescript esno
- Create a
generate:typescommand in yourpackage.jsonfile."generate:types": "esno ./scripts/generate-typescript.ts"(esnoor any other TS script runner)
- Run the command to generate the types.
- It will use
@valibot/to-json-schemato create JSON schema from these schemas. - It will use
json-schema-to-typescriptto create TypeScript types from the JSON.
- It will use
- The types and JSON schemas will be generated in the
typesandschemasfolders in the root of the project.
- You write once code to define the shape of your data.
- You use it in your runtime to validate the data.
- You use it in your frontend:
- Optionally validate the data
- Speak the same language in both runtime and frontend
- If a change is made, you can easily update the code across the project.