sanity-typed icon indicating copy to clipboard operation
sanity-typed copied to clipboard

Adding a nested object filter to GROQ-query results in never

Open studiodrimmel opened this issue 1 year ago • 0 comments

Hi!

First of all, thanks for the effort you've put into this!

Whenever I add a nested filter, the generated type is unknown and it only happens if it is a nested property. It always returns never[] / never

This works fine:

const productSchema = defineType({
    name: 'product',
    type: 'document',
    title: 'Product',
    fields: [
        defineField({
            title: 'Name',
            name: 'name',
            type: 'string'
        })
    ]
})

export const makeTypedQuery = async () =>
    sanityClient.fetch(
    '*[_type=="product"]'
    );

async function test() {
    const res = await makeTypedQuery();
    res[0].name // (Omit<{name?: string | undefined, _createdAt: string, _id: string, _rev: string, _type: "document", _updatedAt: string}, "_type"> & {_type: "product"})[]
}

However when I add some sort of object inside the document and want to query for it it returns a never:

const productSchema = defineType({
    name: 'product',
    type: 'document',
    title: 'Product',
    fields: [
        defineField({
            title: 'Name',
            name: 'name',
            type: 'string'
        }),
        defineField({
            title: 'Store',
            name: 'store',
            type: 'object',
            fields: [
                defineField({
                    title: 'Name',
                    name: 'name',
                    type: 'string'
                })
            ]
        })
    ]
})

export const makeTypedQuery = async () =>
    sanityClient.fetch(
    '*[_type=="product" && store.name == $name]',
        {
            name: 'Search for a name'
        }
    );


async function test() {
    const res = await makeTypedQuery(); // never[]
    res[0].name // Property name does not exist on type never
}

This is a simplified version, as I created custom objects and added them as types to the schemaTypes array. But it still gives a demonstration of the issue.

Am I missing something in my setup for this to work?

Cheers and kind regards, Wesley

Rest of the file:

const config = defineConfig({
    projectId: process.env.SANITY_STUDIO_PROJECT_ID,
    dataset: process.env.SANITY_STUDIO_DATASET,
    schema: {
        types: [
            productSchema
        ]
    },
});
export default config;
export type SanityValues = InferSchemaValues<typeof config>;

export const sanityClient = createClient<SanityValues>()({
    projectId: process.env.SANITY_STUDIO_PROJECT_ID,
    dataset: process.env.SANITY_STUDIO_DATASET,
    apiVersion: process.env.SANITY_STUDIO_API_VERSION || '2023-01-20',
    useCdn: false,
});

studiodrimmel avatar Jan 23 '24 19:01 studiodrimmel