使用ES2015模块语法扩展全局对象 解决Jest扩展触发no-namespace lint报错
等效无namespace语法实现方案
你可以使用TypeScript模块增强语法实现完全相同的功能,完全规避namespace的使用,适配@types/jest v27及以上版本,写法如下:
import type { Matchers } from '@jest/globals'; declare module '@jest/globals' { interface Matchers<R> { toHave: <K>(key: K) => R; } }
如果你的项目依赖的是旧版@types/jest,可以换为扩展jest模块的写法:
import type { Matchers } from 'jest'; declare module 'jest' { interface Matchers<R> { toHave: <K>(key: K) => R; } }
以上两种写法都可以让TypeScript正确识别你自定义的toHave匹配器类型,和你原有的namespace声明功能完全一致,且不会触发@typescript-eslint/no-namespace规则报错。
如果受项目依赖版本限制无法使用上述模块增强写法,也可以通过单行lint忽略注释临时解决问题:
declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace jest { interface Matchers<R> { toHave: <K>(key: K) => R; } } }
内容的提问来源于stack exchange,提问作者Carl Patenaude Poulin
相关产品推荐
相关产品推荐

