如何使用Elasticsearch新版TypeScript类型?返回类型不符如何解决
Elasticsearch Node.js 客户端 TypeScript 类型问题修复方案
7.x版本Elasticsearch Node.js客户端的search方法第一个泛型位默认对应文档源类型,而非返回的Response类型,你直接传入自定义Source类型作为唯一泛型参数时,自然只能拿到_source字段的类型推导,无法得到完整的SearchResponse类型支持。
修复步骤
- 首先从客户端包中引入官方提供的
SearchResponse类型
import type { SearchResponse } from '@elastic/elasticsearch/api/types';
- 调整
search方法的泛型传参,依次传入自定义Source类型、带Source的SearchResponse类型
修改后的完整代码如下:
// 自定义业务文档类型 interface Source { // 按你的业务字段定义即可,示例如下 id: number title: string content: string } // try the new code completion when building a query! const response = await client.search<Source, SearchResponse<Source>>({ index: 'test', body: { query: { match_all: {} } } }) // try the new code completion when traversing a response! const results = response.body.hits.hits.map(hit => hit._source) // results type will be `Source[]`,同时response.body的took、timed_out、total等所有响应字段都具备完整类型提示 console.log(results)
8.x版本适配说明
如果你使用的是8.x及更高版本的客户端,泛型传参逻辑有所调整,无需传两个泛型,直接将SearchResponse<Source>作为唯一泛型参数即可,且请求参数不需要嵌套body层:
const response = await client.search<SearchResponse<Source>>({ index: 'test', query: { match_all: {} } })
内容的提问来源于stack exchange,提问作者blackFlagBaby
相关产品推荐
相关产品推荐

