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

42

我似乎在我的 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
4个回答

65

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

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

这告诉TypeScript我们想跳过node_modules文件夹中库的类型检查。 这可以节省编译时间,并防止节点模块中的冲突类型破坏构建。

对于那些想要一些关于为什么可能需要此选项的解释,这是一个资源链接https://www.typescriptlang.org/tsconfig#skipLibCheck


这是黄金。谢谢。 - Nguyễn Anh Tuấn
1
这个有效。但是有什么问题吗?为什么会有效? - jjmerelo
2
最好不要禁用所有外部库的类型检查。请参见下面@jmoe的答案。 - SamB

30

看起来@types/mocha@types/jest有相似的声明。所以如果你都安装了,需要卸载@types/mocha:

npm uninstall @types/mocha.

这个方法解决了我的问题。


9
这可能可以解释,但也不是解决方案。在我的项目中,我正在使用 mocha,然后安装了另一个间接使用 jest 的依赖项。这导致两者之间产生冲突,并导致编译失败。为了解决这个问题,我不能(也不愿意)简单地停止使用 mocha。 - JHH

1

简而言之:不,你不能将 mocha(以及其他使用 mocha 的测试运行器,例如 web-test-runner)放在同一个模块中。

类型只能定义一次,mochajest 声明了一系列全局变量(需要这样做才能直接使用而无需导入),这些变量彼此不兼容。你需要选择其中一个,或者如果你使用诸如 web-test-runnerelectron-mocha 等工具,则选择另一个运行器(例如 cypress)。

任何解决方法都会隐藏其中一个,因此最终你不能同时使用它们。总的来说,将两个测试运行器声明为依赖项可能不是一个好主意,所以最好重构代码以选择其中一个。


-4

你可以用 @types/jest 替代 @types/mocha


2
他两个都有。 - Javi Marzán
12
为什么这是一个回答并且为什么它得到了任何投票? - notAChance
看起来,mocha和jest都声明了beforeEach钩子,这可能是错误的原因。 - Julius Žaromskis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接