You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vitest中使用全局Provide时,注入为何触发TypeScript错误?

从Jest迁移至Vitest时全局变量类型错误的解决

问题场景

我正从Jest迁移至Vitest,需要提供全局变量(如用户ID)以在测试中关联相关内容,但TypeScript无法识别uid的有效类型,抛出错误:Argument of type string is not assignable to parameter of type never。

相关代码

setupTests.ts

import type { GlobalSetupContext } from 'vitest/node';

export default function setup({ provide }: GlobalSetupContext) {
  const now = Date.now();

  // 功能正常,但TypeScript报错
  provide('uid', `test-user-${now}`);
}

declare module 'vitest' {
  export interface ProvidedContext {
    uid: string;
  }
}

BaseModel.test.ts

...
// 功能正常,但TypeScript报错
const uid = inject('uid');
...

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  },
  "compileOnSave": true,
  "exclude": [
    "lib",
    "node_modules"
  ],
  "include": [
    "src"
  ],
  "types": [
    "vitest/globals",
    "./setupTests.ts"
  ]
}

解决方法

  • 确保类型声明文件被TypeScript识别:当前tsconfig.json的include仅包含src目录,如果setupTests.ts在项目根目录,TypeScript不会加载它的类型扩展。修改include配置:
    "include": [
      "src",
      "setupTests.ts"
    ]
    
  • 验证模块扩展的正确性:declare module 'vitest'代码块会合并Vitest内置的ProvidedContext接口,确保这段代码能被TypeScript正确解析,为provide和inject函数提供正确的类型提示。
  • 单独抽离类型声明(可选):如果上述调整后仍有问题,可将类型声明单独放在src/vitest.d.ts文件中(确保在include范围内),内容如下:
    declare module 'vitest' {
      export interface ProvidedContext {
        uid: string;
      }
    }
    

完成以上调整后,TypeScript就能正确识别uid的类型,不再抛出错误。

内容的提问来源于stack exchange,提问作者MorganEngel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 06:36:14