TypeScript 错误 TS2403:后续变量声明必须具有相同的类型

问题描述 投票:0回答:5

我的 TypeScript 项目似乎遇到了一些编译错误。完整的错误是:

node_modules/@types/mocha/index.d.ts:2680:13 - error TS2403: Subsequent 
variable declarations must have the same type.  Variable 'beforeEach'
must be of type 'Lifecycle',  but here has type 'HookFunction'.

2680 declare var beforeEach: Mocha.HookFunction;
                 ~~~~~~~~~~

我有 7 个这样的错误,全部都在同一个依赖项(Mocha)中。我正在使用 TypeScript

^3.3.3
,这是我的
tsconfig.json
:

{
  "compilerOptions": {
    "composite": false,
    "declaration": true,
    "declarationMap": true,
    "removeComments": true,

    "target": "es2017",
    "lib": ["dom", "es2015", "es2016", "es2017"],
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true,

    "jsx": "preserve",
    "allowJs": false,
    "strict": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "outDir": "build",
    "noUnusedParameters": true,

    "noUnusedLocals": false,

    "baseUrl": ".",
    "paths": {
      "*": ["./types/*"],
    },

    "rootDir": "./src",

    "typeRoots": ["./@types", "./node_modules/@types"]
  },

  "exclude": [
    "node_modules",
    "build",
    "dist",
    "__mocks__",
    "__tests__",
    "coverage",
    "*.config.js",
    "*.babel.js",
    "*.test.ts",
    "specs"
  ]
}

此外,这些是我的开发依赖项:

"devDependencies": {
  "@types/jest": "^24.0.9",
  "@types/koa": "^2.0.48",
  "@types/lodash": "^4.14.121",
  "@types/mocha": "^5.2.6",
  "@types/twig": "^1.12.2",
  "@types/uuid": "^3.4.4",
  "chai": "^4.1.2",
  "concurrently": "^4.1.0",
  "db-migrate": "^0.11.5",
  "dotenv": "^6.0.0",
  "grunt": "^1.0.3",
  "grunt-cli": "^1.2.0",
  "jest": "^23.1.0",
  "nodemon": "^1.17.2",
  "ts-jest": "^23.10.5",
  "ts-node": "^8.0.2",
  "tslint": "^5.14.0",
  "typescript": "^3.3.3"
}

这是我的编译命令:

tsc src/index.ts
typescript compiler-errors mocha.js
5个回答
70
投票

我将以下属性添加到 tsconfig 文件中

"compilerOptions": {
    "skipLibCheck": true
},

这告诉 TypeScript 我们要跳过 node_modules 文件夹中库的类型检查。这可以节省编译时间并阻止节点模块中的冲突类型破坏构建。 对于那些想要解释为什么需要此选项的人,这里有一个资源链接 https://www.typescriptlang.org/tsconfig#skipLibCheck


31
投票

看起来

@types/mocha
@types/jest
有类似的声明。因此,如果您两者都有,请卸载
@types/mocha

npm uninstall @types/mocha
.

这解决了我的问题。


1
投票

TL;DR:不,您不能将

mocha
(以及使用
mocha
的其他测试运行程序,例如
web-test-runner
)放在同一个模块中。

类型只能定义一次,并且

mocha
jest
声明了一系列彼此不兼容的全局变量(需要这样它们才能直接使用而无需导入)。您需要致力于其中一个,或者如果您使用诸如
web-test-runner
electron-mocha
之类的东西,只需选择另一个跑步者(例如,
cypress
就可以)。

任何解决方法都会隐藏其中一个,因此最终您无法一起使用它们。归根结底,将两个测试运行程序声明为依赖项可能不是一个好主意,因此您不妨重构代码以选择其中一个。


0
投票

就我而言,我使用 Jest 进行单元测试,但我们管道中的集成测试使用的库正在传递安装

@types/mocha
。我不需要 Mocha 类型,所以我创建了一个
mocha.d.ts
文件并添加了

declare module 'mocha' {}

它会覆盖 Mocha 类型,而无需卸载任何内容或跳过库检查。


-4
投票

您可以将

@types/mocha
替换为
@types/jest

© www.soinside.com 2019 - 2024. All rights reserved.