Sanity Typegen doesn't resolve dynamic language mapping in GROQ

23 hours ago 3
ARTICLE AD BOX

I am using sanity typegen with Next.js and I have localized fields in my Sanity schema. In my GROQ queries, I use a $lang variable to pick the correct translation. While the query works perfectly at runtime and returns a string, the generated TypeScript types still treat the field as the full localized object (e.g., { pl: string, en: string }).

Schema :

defineField({ name: 'title', type: 'object', fields: [ { name: 'pl', type: 'string' }, { name: 'en', type: 'string' } ] })

Query:

const HERO_QUERY = defineQuery(` *[_type == "home"][0] { "heading": heading[$lang] } `);

Generated type (types.ts)

export type HERO_QUERY_RESULT = { heading: { pl?: string; en?: string; } | null; };

Expected Type:
The heading should be inferred as string | null because of the [$lang] mapping in the query.

Question:
Is there a way to make sanity typegen understand that dynamic indexing via $lang results in a string, or do I have to manually override/cast these types every time I use them in my components?

PS: This soultion works but typescript is shouting at me, don't want to do ts-expect-error before every line

Read Entire Article