
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeLooking at your issue, this is a common point of confusion with Sanity TypeGen. When you mark a field as required in your schema using validation: rule => rule.required(), TypeGen will still generate the field as optional (with | null) by default.
This happens because TypeGen is designed to be conservative - even if a field is required for published documents, draft documents can be in an "invalid" state while being edited. If you're querying drafts or using perspectives that include unpublished content, those fields might legitimately be undefined or null.
To make TypeGen respect your required validation rules and generate non-optional types, you need to use the --enforce-required-fields flag when extracting your schema:
npx sanity schema extract --enforce-required-fields
npx sanity typegen generateThis will generate types where fields marked with .required() validation are not optional (no ? or | null).
However, be aware that if you're working with draft documents or using the previewDrafts perspective, values can still be undefined or null even for "required" fields, since validation is only enforced on published documents. So you may need runtime checks even with this flag enabled.
When you write GROQ queries and use TypeGen to generate types for query results, the same principle applies. If you project a field in your GROQ query:
const query = defineQuery(`*[_type == "page"]{ pageData }`)TypeGen will look at your schema definition for pageData. If it's marked as required and you used --enforce-required-fields, it won't be nullable in the generated query result type. Without that flag, it will be pageData: PageData | null even if the schema says it's required.
The key understanding is that TypeGen generates types based on what could exist in your Content Lake, not just what's valid for published documents. This is documented in the Sanity TypeGen documentation under the "Required field validation and non-optional fields" section.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store