Unlock seamless workflows and faster delivery with our latest releases- get the details

Typing issue with `context.parent` in custom validation in Sanity.io

9 replies
Last updated: May 23, 2023
Hello! just wondering if there’s a correct way to type
context.parent
when writing custom validation as it returns the
unknown
type by default. Thank you!
May 23, 2023, 12:30 AM
Looks like it should be the type of the data for the field you're validating, which would be sensible, and looks correct for the example here: https://www.sanity.io/docs/validation#091e10f957aa
May 23, 2023, 1:40 AM
Looks like it should be the type of the data for the field you're accessing, doesn't it?
And then you can assign that type to the value you pull out of context.

In looking at your code, presumably the parent has an array field, actually, since you're interested if there would be more than one image ii nit, which doesn't seem it would be named 'image'?

And then you'd be checking for arrayField.length > 1, or maybe testing further using something like arrayField.reduce to count items of a certain type, etc.?

So if you're having a problem where types might help, may want to consider these also.

Hope I understood your question ,
user G
May 23, 2023, 1:59 AM
This seems it works well for the typing issue -- I always want to test, when it's Typescript involved....
type aContext = {
  parent: {
    name: string
  }
}

 rule.custom((value, context) => {
          
          const { parent } = context as aContext
          const { name } = parent
          console.log ('parent name: ' + name)

   ...
The
as
is a Typescript cast -- as you can't just redefine an
any
variable. Pretty handy, here anyway....
May 23, 2023, 2:26 AM
Thanks for your help! This is what I ended up doing as well. I was just wondering if there’s something built-in to Sanity that allows me to automatically infer types for the specific field under the parent.
May 23, 2023, 2:29 AM
I guess it isn’t possible for Sanity to know, hence what parent is typed as
unknown
and we’d just need to type it manually
May 23, 2023, 2:30 AM
Great -- and as far as automatic function, not immediately imagining how it could act in time for Typescript to see it, unless it was really an intelligent editor that did this for you, and wrote it in.
I suspect for that, we may live in hope, as someone once said!
May 23, 2023, 2:32 AM
really appreciate your help!
May 23, 2023, 2:32 AM
most welcome, Ryan 🙂
May 23, 2023, 2:33 AM
(and actually the WebStorm I'm using could have the knowledge, I think, if it understood Sanity schemas. Which when we use the defineXXX, it at least comes close...
May 23, 2023, 2:36 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?