You need to enable JavaScript to run this app. 使用ES2015模块语法扩展全局对象 解决Jest扩展触发no-namespace lint报错
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 19:00:02