【问题标题】:How to get the type of Algolia search results?如何获取 Algolia 搜索结果的类型?
【发布时间】:2020-10-03 04:42:02
【问题描述】:

我的firestore 正在与algoliasearch 连接。我使用typescriptnextjs

我尝试得到如下结果

products = index.search(name).then(({hits}) => {
  return hits
})

然后我将结果存储在一个状态中,这样我就可以将它们作为道具传递给另一个组件。 但是,我经常收到关于类型 ObjectWithObjectID 的错误。我已经安装了@types/algoliasearch,但我似乎找不到ObjectWithObjectID 的道具。有什么解决方法吗?

【问题讨论】:

    标签: reactjs typescript full-text-search next.js algolia


    【解决方案1】:

    我必须手动输入“命中”的样子,例如:

    type AlgoliaHits = {
      hits: AlgoliaHit[];
    };
    
    export type AlgoliaHit = {
      identifier: string;
      cpi_visibility: string;
      title: string;
      published: string;
    };
    
    const content: AlgoliaHits = await index.search(searchText, {
      hitsPerPage: HITS_PER_PAGE,
      facetFilters: ["cpi_visibility:published"].filter(Boolean)
    });
    

    【讨论】:

      【解决方案2】:

      在索引上调用.search 允许将类型作为泛型传递。这会将返回的hits 的类型指定为与给定的相同类型。

      const content = await index.search<AlgoliaHit>(searchText, {
        hitsPerPage: HITS_PER_PAGE,
        facetFilters: ["cpi_visibility:published"].filter(Boolean)
      });
      

      这也将为content 提供SearchResponse&lt;AlgoliaHit&gt; 类型,这将为您提供content 上可用属性的一些不错的自动完成功能;

      content.hits.map(hit => 
        console.log(hit, "<- this has every property that you've defined in AlgoliaHit")
      )
      

      【讨论】:

        猜你喜欢
        • 2016-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-10
        • 2018-07-30
        • 2015-12-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多