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

Luk*_*uke 18 compiler-errors mocha.js typescript

我的 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;
                 ~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

我有 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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

"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"
}
Run Code Online (Sandbox Code Playgroud)

这是我的编译命令:

tsc src/index.ts
Run Code Online (Sandbox Code Playgroud)

Jam*_*sis 13

看起来@types/mocha@types/jest有类似的声明。因此,如果您同时拥有两者,请卸载@types/mocha

npm uninstall @types/mocha.

这为我解决了这个问题。

  • 这可以解释它,但这也不是解决方案。在我的项目中,我使用“mocha”,然后安装了另一个间接使用“jest”的依赖项。这就造成了两者冲突,编译失败。我不能(不会)简单地停止使用摩卡来解决这个问题。 (8认同)

小智 12

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

"compilerOptions": {
    ...
    "skipLibCheck": true   },
Run Code Online (Sandbox Code Playgroud)

  • 不禁用所有外部库的类型检查可能是一个更好的主意。请参阅下面@jmoe 的回答。 (2认同)