TypeScript Results of Hits does not Exists on Type

I have this code for querying products:

index.search('', {
   length: 5,
   attributesToRetrieve: ['handle'],
   filters: 'inventory_quantity>0',
}).then((hits) => {
   console.log(hits.hits[0].handle)
})

I want to loop on hits.hits which has a content of :

  {
    handle: 'id859156',
    objectID: '32184438685814',
    _snippetResult: { body_html_safe: [Object] },
    _highlightResult: {
      vendor: [Object],
      tags: [Array],
      sku: [Object],
    }
  },
  {
    handle: 'id859157',
    objectID: '32184438489206',
    _snippetResult: { body_html_safe: [Object] },
    _highlightResult: {
      vendor: [Object],
      tags: [Array],
      sku: [Object],
    }
  }
]

I can print the contents of hits.hits[0].handle, but the VSCode says Property 'handle' does not exist on type '{ readonly objectID: string; readonly _highlightResult?: {} | undefined; readonly _snippetResult?: {} | undefined; readonly _rankingInfo?: RankingInfo | undefined; readonly _distinctSeqID?: number | undefined; } why?

1 Like
index
  .search<{ handle: 'string' }>('', {
    length: 5,
    attributesToRetrieve: ['handle'],
    filters: 'inventory_quantity>0',
  })
  .then((hits) => {
    console.log(hits.hits[0].handle);
  });

you have to pass the generic to access keys in the record that aren’t defined by default. There’s an example here: competent-architecture-xo8gn - CodeSandbox (replace with your own index to make it work)

Have a nice day!