How Sanity TypeGen works
A run has two commands.
sanity schema extractcreates a staticschema.jsonsnapshot of the Studio schema, which TypeGen reads.sanity typegen generatewrites all schema and query types to asanity.types.tsfile by default.
Only queries assigned to a uniquely named variable get types. An inline query passed straight to fetch is skipped. TypeGen picks up queries from TypeScript, JavaScript, Astro, Svelte and Vue files. With a query written in defineQuery, the Sanity client infers the result type of fetch automatically once types are generated.
GROQ expressions TypeGen cannot analyze get the type unknown and the run carries on. Fields with required() validation become non-optional in the types only when the schema is extracted with --enforce-required-fields. Flags and options are listed in the Sanity TypeGen documentation.
Configuration and versions
Requirements. The current docs list Sanity Studio v5.10.0 or later, a Studio schema and GROQ queries assigned to variables.
Config location. Settings sit in the
typegenblock ofsanity.cli.ts, and the separatesanity-typegen.jsonfile is deprecated.Automatic runs. With
typegen.enabledset to true, types regenerate duringsanity devandsanity build.Watch mode. Since v5.8.0, schema extraction and type generation both take a
--watchflag, the recommended mode for a frontend in a separate repository.Client typing. The
overloadClientMethodsoption insanity.cli.tsturns automatic client typing off.Nested types. The
Getutility type from@sanity/codegenpulls deeply nested types out of generated types, up to 20 levels, which helps with page builder schemas.Global registry. From Studio v6.13.0, query result types are registered on a global
SanityQueriesinterface, so they work across every copy of@sanity/client.
Sanity says GA means the configuration format, CLI commands and utility types will not change in breaking ways. For the CMS behind these types, see what Sanity is and how it works.
How Pagepro uses TypeGen
TypeGen is part of the core architecture of Nexity, the delivery system Pagepro uses in its Sanity development work to migrate legacy web stacks to Next.js and Sanity on Vercel. Nexity runs TypeScript in strict mode, and TypeGen generates its Sanity types.
Sources
- Sanity TypeGenSanity · sanity.io
- Sanity Studio v5.10.0: TypeGen GA, and improvements to Portable Text Editor, Media Library plugin, comments, timezone UI, and file uploadsSanity · sanity.io
- Sanity Studio v6.13.0: Portable TypeGen types, keepPanesOnCreate for Structure, and diagnostics upgradesSanity · sanity.io
- Sanity TypeGen is now generally availableSanity · sanity.io