
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeWhen writing custom validation in Sanity, context.parent returns the unknown type by default, which is intentional since TypeScript can't automatically infer the parent's structure. The solution is to manually type it using a TypeScript type assertion with the as keyword.
Here's the recommended approach:
type ParentContext = {
parent: {
// Define the structure of your parent object
fieldName: string
anotherField: number
// ... other fields
}
}
defineField({
name: 'myField',
type: 'string',
validation: (rule) => rule.custom((value, context) => {
const { parent } = context as ParentContext
const { fieldName } = parent
// Now you have proper typing for parent fields
if (parent.fieldName === 'something') {
return 'Validation error message'
}
return true
})
})Unfortunately, there isn't a built-in Sanity type that automatically infers the parent structure. The parent property is typed as unknown because Sanity can't know the specific schema structure at compile time. This means you'll need to manually define the type based on your schema.
Why this approach works:
as keyword is a TypeScript type assertion that tells the compiler to treat context as having your defined structureIf you're working with generated TypeScript types from your schema using Sanity TypeGen, you can reference those types in your validation context definition to keep things in sync. This is the cleanest approach since your parent types will automatically update when your schema changes.
As discussed in this community thread, this is the standard pattern for handling typing in custom validation rules where you need access to parent or document context. While it would be nice if IDEs could automatically understand Sanity schemas and provide this typing, for now manual type definitions are the way to go.
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