添加vitest.d.ts自定义匹配器后,Vitest的TypeScript支持失效
问题描述
我通过expect.extend编写了一个自定义匹配器:
expect.extend({ toEqualIgnoringWhitespace(got: string, want: string) { return { pass: got.trim().replace(/\s+/g, ``) === want.trim().replace(/\s+/g, ``), message: () => `Even with whitespace removed, ${got} does not equal ${want}.` }; } });
按照Vitest文档建议添加了vitest.d.ts文件:
interface CustomMatchers<R = unknown> { toEqualIgnoringWhitespace: () => R } declare module 'vitest' { type Assertion<T = any> = CustomMatchers<T> interface AsymmetricMatchersContaining extends CustomMatchers {} }
并在tsconfig.json的include中加入该文件:
"include": ["vitest.d.ts","env.d.ts", "**/*.ts", "**/*.tsx"],
但现在TypeScript无法识别Vitest的其他内容,test.extend、use和task均隐式为any类型,导入expect等常规内容也无法被识别,仅能识别自定义匹配器相关内容。
解决方案
问题出在你直接用type Assertion<T = any> = CustomMatchers<T>覆盖了Vitest原生的Assertion类型,导致原有类型全部丢失。正确的做法是扩展Vitest的原有接口,而非替换。
步骤1:修正vitest.d.ts文件
修改文件内容,改为扩展原生接口:
// 导入Vitest原生类型,确保能基于原有接口扩展 import type { Assertion, AsymmetricMatchersContaining } from 'vitest'; interface CustomMatchers<R = unknown> { // 修正匹配器参数定义,需要传入预期值 toEqualIgnoringWhitespace(want: string): R; } declare module 'vitest' { // 扩展原生Assertion接口,添加自定义匹配器 interface Assertion<T = any> extends CustomMatchers<T> {} interface AsymmetricMatchersContaining extends CustomMatchers {} }
步骤2:确保tsconfig.json加载Vitest类型
检查compilerOptions.types是否包含vitest,保证原生类型能被正确识别:
{ "compilerOptions": { "types": ["vitest"] }, "include": ["vitest.d.ts","env.d.ts", "**/*.ts", "**/*.tsx"] }
完成以上修改后,TypeScript就能同时识别自定义匹配器和Vitest的原生API了。
内容的提问来源于stack exchange,提问作者Jonathan Tuzman
相关产品推荐
相关产品推荐

