Sanity
Learn
CoursesTyped content with Sanity TypeGenGenerating types for GROQ query results
Track
Sanity Developer Certification

Typed content with Sanity TypeGen

Lesson
5

Generating types for GROQ query results

Make your queries discoverable. Generate TypeScript types for your GROQ queries.

Log in to mark your progress for each Lesson and Task

With the TypeGen configuration set up to look for GROQ queries in your front end project, the last step is to make those queries discoverable for the tooling.

First, go into your front end folder. If you follow this course with the code from the Day One course, you can search for EVENTS_QUERY to find the index route file.

./src/app/page.tsx
const EVENTS_QUERY = `*[_type == "event" && defined(slug.current)]{_id, name, slug, date}|order(date desc)`;
Open the file with the EVENTS_QUERY

To get types for GROQ query results from the TypeGen, you need to make sure of the following:

  • The string with the query is assigned to a variable
  • The variable name needs to be globally unique since it’s used for the type name
  • The string needs to be a syntactically valid GROQ query (for example, you should be able to run it successfully in the Vision plugin or on groq.dev)
  • The string with the query needs to be prefixed with the groq template literal

The EVENTS_QUERY is only missing the last point to be picked up by the TypeGen command.

If you’re using Next.js, you can import groq from the next-sanity package.

For other frameworks, you can install the groq package:

Terminal
npm i groq

Add the groq template literal like this; remember to save the file after:

import { groq } from 'next-sanity'
// import groq from 'groq' // in other frameworks
const EVENTS_QUERY = groq`*[_type == "event" && defined(slug.current)]{_id, name, slug, date}|order(date desc)`;
Import groq into the route file with the EVENTS_QUERY variable
Add the groq template literal to your GROQ query string

The primary function of the groq template literal is to make it easier for the code editor to add syntax highlighting. It’s also used by the TypeGen tooling to identify something as a GROQ query.

Return to the Studio folders and run the sanity typegen generate command again. It should pick up the GROQ query, and the output should be like this:

Terminal
✔ Generated TypeScript types for 14 schema types and 1 GROQ queries in 1 files into: ../frontend/src/sanity/types.ts

Open your types.ts file in your front end folder, and search for EVENTS_QUERY to find your new type:

./src/sanity/types.ts
// Source: ../frontend/src/app/page.tsx
// Variable: EVENTS_QUERY
// Query: *[_type == "event" && defined(slug.current)]{_id, name, slug, date}|order(date desc)
export type EVENTS_QUERYResult = Array<{
_id: string;
name: string | null;
slug: Slug | null;
date: string | null;
}>;
Find the EVENTS_QUERYResult type in types.ts

The next step is to learn how to use this type in your front end code.