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

如何在TypeScript库中导出Vitest自定义匹配器的类型增强?

解决Vitest自定义匹配器库的类型导出问题

要让导入你库的项目自动识别自定义匹配器的类型,需要调整类型声明的配置和结构,具体步骤如下:

1. 规范类型增强的声明文件结构

不要把类型增强仅放在本地的vitest.d.ts,而是在库源码中单独创建类型文件(比如src/vitest-extensions.d.ts),并正确扩展Vitest的类型接口:

// src/vitest-extensions.d.ts
import type { Assertion, AsymmetricMatchersContaining } from 'vitest'

declare module 'vitest' {
  // 扩展expect()返回的Assertion类型
  interface Assertion<T = any> {
    toMatchTheTypicalExpectations(): void
  }

  // 可选:扩展不对称匹配器类型(如果需要)
  interface AsymmetricMatchersContaining {
    toMatchTheTypicalExpectations(): void
  }
}

2. 配置TypeScript打包生成类型文件

确保你的tsconfig.json开启类型声明生成,并包含上述文件:

{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "./dist/types",
    "emitDeclarationOnly": false, // 若单独生成类型可设为true
    "include": ["src/**/*"]
  }
}

3. 在package.json中配置类型导出入口

让外部项目能自动找到你的类型文件,需在package.json中明确类型入口:

方式一:简单库配置(适用于单一入口)

直接指定types字段指向主类型文件(确保主类型文件或其依赖包含了类型增强代码):

{
  "name": "your-library",
  "types": "./dist/types/index.d.ts",
  "main": "./dist/index.js",
  "module": "./dist/index.mjs"
}

方式二:多入口配置(推荐,区分核心代码和匹配器)

用exports字段更精准地导出不同入口的类型和代码,方便使用者按需导入:

{
  "exports": {
    ".": {
      "types": "./dist/types/index.d.ts",
      "import": "./dist/index.mjs",
      "require": "./dist/index.js"
    },
    "./vitest": {
      "types": "./dist/types/vitest-extensions.d.ts",
      "import": "./dist/vitest-extensions.mjs",
      "require": "./dist/vitest-extensions.js"
    }
  },
  "types": "./dist/types/index.d.ts"
}

4. 确保类型增强被自动加载

如果使用者通过import 'your-library/vitest'导入匹配器注册代码,TypeScript会自动加载对应入口的类型文件。另外,也可以在库的主类型文件中导入类型增强文件,确保只要导入库就会加载类型:

// src/index.ts
import './vitest-extensions.d.ts'
// 库的其他代码...

5. 验证打包结果

打包后检查dist/types目录下是否包含了vitest-extensions.d.ts或整合了该增强的类型文件,然后创建一个测试项目安装你的库,编写测试代码验证类型是否正常识别:

import { expect, test } from 'vitest'
import 'your-library/vitest'

test('test custom matcher', () => {
  const data = {}
  expect(data).toMatchTheTypicalExpectations() // 此时不应触发TS2339错误
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:55:19