Sanity-codegen query with projection not working as expected
Your GROQ query *[_type == "country"] { 'slug': slug.current } is perfectly valid syntax and should work fine with sanity-codegen's client! The query itself isn't the problem.
However, I need to give you some important context: sanity-codegen has been archived and is no longer actively maintained. It's been superseded by Sanity's official TypeGen tooling, which was released in March 2024.
Without seeing the specific error you're getting, here are the most likely issues:
If you're getting type errors:
The sanity-codegen client's query<T>() method should handle projections, but you might need to explicitly type the result:
interface CountrySlug {
slug: string;
}
const allCountries = await client.query<CountrySlug[]>(
'*[_type == "country"] { "slug": slug.current }'
);Note: Use "slug" (with quotes) instead of 'slug' in your projection - both work in GROQ, but double quotes are the standard convention.
Recommended: Migrate to Official TypeGen
Since sanity-codegen is archived, I'd strongly recommend migrating to the official solution. It provides better type inference and is actively maintained:
npx sanity@latest typegen generateThen use defineQuery for automatic type inference:
import { defineQuery } from 'next-sanity'; // or 'groq'
import { sanityFetch } from './lib/client';
const COUNTRIES_QUERY = defineQuery(
'*[_type == "country"] { "slug": slug.current }'
);
const allCountries = await sanityFetch({ query: COUNTRIES_QUERY });
// TypeScript automatically knows the shape!The official TypeGen creates a sanity.types.ts file with types for your entire schema and automatically infers types from your GROQ queries - no manual type annotations needed.
If you want to stick with sanity-codegen for now, can you share the specific error message you're seeing? That would help diagnose whether it's a type issue, runtime error, or something else.
Show original thread17 replies
Sanity ā Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.