Add Type-safety to your project and reduce the likelihood that you will write code that produces errors.
In the case of working with Sanity TypeGen, it can create Types for Sanity Studio schema types and GROQ query results. So, as you build out your front end, you only access values within documents that exist, as well as defensively code against values that could be null
.
sanity typegen
command.Sanity TypeGen will create Types for queries that are assigned to a variable and use the defineQuery
function.
You're able to use the Sanity CLI from inside the Next.js application because of the sanity.cli.ts
file at the root of your project.
npx sanity@latest schema extract --path=./src/sanity/extract.json
The --path
argument is provided so the schema file is written to the same folder as all our other Sanity utilities.
You should see a response like the one below and a newly generated schema.json
file in your src/sanity
directory
✅ Extracted schema
This file contains all the details about your Sanity Studio schema types, which TypeGen will need to create types from.
By default, TypeGen will create a file for types at the project's root. Again, to keep Sanity-specific files colocated, we can preconfigure some defaults and keep the project root tidy.
{ "path": "./src/**/*.{ts,tsx,js,jsx}", "schema": "./src/sanity/extract.json", "generates": "./src/sanity/types.ts"}
The configuration here will:
- Scan the
src
directory for GROQ queries to create Types. - Additionally, use the
extract.json
file created during the previous task. - Write a new
types.ts
file with our other Sanity utilities.
npx sanity@latest typegen generate
You should see a response like the one below and a newly created src/sanity/types.ts
file in your project.
✅ Generated TypeScript types for 15 schema types and 2 GROQ queries in 1 files into: ./src/sanity/types.ts
Success! You now have Types for your Sanity Studio schema types and GROQ queries.
The extract.json
file will need to be updated every time you update your Sanity Studio schema types and TypeGen every time you do or update your GROQ queries.
Instead of doing these steps separately, you can include scripts in your package.json
file to make running these automatic and more convenient.
package.json
scripts"scripts": { // ...all your other scripts "predev": "npm run typegen", "prebuild": "npm run typegen", "typegen": "sanity schema extract --path=./src/sanity/extract.json && sanity typegen generate"},
You can now run both the schema extraction and TypeGen commands with one line:
npm run typegen
You now have all the tools and configurations to author and query Sanity content with a Type-safe, excellent developer experience. Now it's finally time to query and display Sanity content.