TypeScript中Testing Library的within返回类型适配问题
替换Testing Library辅助函数中的any类型方案
注:within是getQueriesForElement的别名,其定义可查看Testing Library类型源码中get-queries-for-element.d.ts文件的第178-182行内容。
解决步骤
- 导入所需类型:从
@testing-library/react(或@testing-library/dom)中导入对应类型,这些类型对应Testing Library的查询方法集合:
import { Screen, BoundFunctions, Queries } from '@testing-library/react';
- 修改辅助函数类型:将
container参数的any替换为BoundFunctions<Queries>,这就是within方法返回对象的正确类型,最终函数定义如下:
const getSomething = (name: string, container: Screen | BoundFunctions<Queries> = screen) => { return container.getByRole('someRole', { name }); };
类型说明
BoundFunctions<Queries>:代表绑定到指定元素容器上的查询方法集合,正是within调用后的返回类型,包含getByRole等所有Testing Library查询方法。Screen类型本身继承了BoundFunctions<Queries>,因此这个联合类型可以同时兼容全局screen对象和within返回的容器对象,完全覆盖你的使用场景。
内容的提问来源于stack exchange,提问作者lcoq
相关产品推荐
相关产品推荐

