Define() - Is there a way to define the define()?

11 replies
Last updated: Jun 1, 2022
Is there a way to define the
define()
at a higher level, or some other way to apply that function to all fields? It's getting a bit verbose to add this to all fields.
*[_type == "resource"] {
  _id,
    "slug": slug.current,
    title,
    defined(subtitle) => {subtitle},
    defined(content) => {content},
    description,
    defined(keywords) => {keywords},
    defined(video.url) => {"video": video.url},
    "asset": {
      defined(external) => {"external": asset.external},
      defined(internal) => {"internal": asset.internal.asset->url}
    },
    categories[]->{_id, title},
   "poster": poster.asset-> {
     ...,
     "lqip": metadata.lqip
   }
}
May 24, 2022, 10:35 AM
Why do you worry that much about discarding these fields?
May 24, 2022, 10:36 AM
I'm using a type system for decoding the response (
io-ts
), to have runtime type checking (100% guarantee of correct types).
If my type is
label?: string
(optional string), then
label: string | null
returned from sanity will not be a valid type.
May 24, 2022, 10:41 AM
Interesting. Then I guess you gotta do what you gotta do.
May 24, 2022, 10:41 AM
I can also change my types to
label: string | null
which will work, but prefer just using the
defined()
function.
May 24, 2022, 10:42 AM
Unfortunately, no. But we have on our roadmap to fix this. We definitely see that most people don’t expect nulls for missing data.
May 24, 2022, 11:16 AM
user L
Great to hear it's being looked at. 🙂
May 24, 2022, 3:02 PM
Would be fun to see/read how your using your super TS stuff some time
user F
😁
May 24, 2022, 4:03 PM
I might do a write up of it. Some neat stuff going on. 😄
May 24, 2022, 4:12 PM
As stated, they are fixing this. It's the single reason I'm on api v1 versus v2. C’mon v3!
May 26, 2022, 3:26 PM
user A
I did end up writing an article about this approach. 😊 https://madebymist.com/text/fetch-runtime-type-safe-data-from-sanity-using-io-ts
Jun 1, 2022, 6:31 PM
Thanks a bunch :D
Jun 1, 2022, 6:31 PM

Sanity.io – build remarkable experiences at scale

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