Typing context.parent in Sanity custom validation
When 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:
- The
askeyword is a TypeScript type assertion that tells the compiler to treatcontextas having your defined structure - You define the exact shape of the parent object based on your schema
- This gives you full type safety and autocomplete for parent fields
If 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.
Show original thread9 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.