如何在TypeScript中将Algolia搜索结果转换为自定义接口
Algolia + TypeScript:将搜索结果转换为自定义类型数组
我正在使用Algolia搭配TypeScript开发,搜索返回的结果结构如下:
{ hits: [ { author: 'Author 1', eventCategory: 'Major', book: 'My Book1', eventStarTime: 1683081900, eventID: 2323213, objectID: 'o-871278123', _highlightResult: [Object] }, { author: 'Author 1', eventCategory: 'Major', book: 'My Book2', eventStarTime: 1683084000, eventID: 2344244, objectID: 'o-871278456', _highlightResult: [Object] } ], nbHits: 2, page: 0, nbPages: 1, hitsPerPage: 20, exhaustiveNbHits: true, exhaustiveTypo: true, exhaustive: { nbHits: true, typo: true }, query: '', params: 'filters=isAuthor+%3D+1', processingTimeMS: 1, processingTimingsMS: { request: { queue: 4, roundTrip: 4 } }, serverTimeMS: 4 }
我希望把结果解析为仅包含author、eventCategory、book、eventStarTime、eventID、objectID字段的自定义接口数组,尝试了以下代码:
const searchResponse: SearchResponse = await index.search('', { filters: filters, attributesToRetrieve: ['author', 'eventCategory','book','eventStarTime','eventID'], }); const hits: Array<Hit<TObject>> = searchResponse.hits;
请问如何将结果转换为Array<Hit<TObject>>类型?Hit和TObject是否可以导入?
1. 定义自定义TObject接口
首先需要自己定义TObject接口,对应你关注的字段:
interface TObject { author: string; eventCategory: string; book: string; eventStarTime: number; eventID: number; objectID: string; }
2. 导入Algolia的官方类型
Hit和SearchResponse都是Algolia官方提供的TypeScript类型,可以直接从对应包中导入:
- 如果你用的是基础
algoliasearch包:
import { SearchResponse, Hit } from 'algoliasearch';
- 如果你用的是拆分后的
@algolia/client-search包:
import { SearchResponse, Hit } from '@algolia/client-search';
3. 正确的类型转换写法
在调用search方法时,直接传入泛型参数指定你的自定义类型,返回结果会自动推导为目标类型,无需额外手动转换:
// 传入泛型TObject,明确返回结果的结构 const searchResponse: SearchResponse<TObject> = await index.search<TObject>('', { filters: filters, // 注意:objectID是Algolia默认返回字段,但如果指定了attributesToRetrieve,建议显式添加它 attributesToRetrieve: ['author', 'eventCategory', 'book', 'eventStarTime', 'eventID', 'objectID'], }); // 此时hits自动为Array<Hit<TObject>>类型,无需额外断言 const hits = searchResponse.hits;
如果因特殊场景需要手动转换,可使用类型断言:
const hits = searchResponse.hits as Array<Hit<TObject>>;
关键说明
Hit<T>是Algolia的通用包装类型,它会包含你自定义的T字段,以及Algolia默认生成的_highlightResult、_snippetResult等元字段(如果开启了高亮/片段功能)。- 确保
attributesToRetrieve包含TObject中定义的所有字段,避免出现类型不匹配问题。
内容的提问来源于stack exchange,提问作者Spartacus
相关产品推荐
相关产品推荐

