同时发生“无法在没有新的情况下调用类”和“无法重新声明被阻塞的变量”

问题描述

尝试使用RESTDataSource时出现错误

"Class constructor RESTDataSource cannot be invoked without 'new'"

因此,我尝试了this解决方案并添加"target": "es2016"。我不再收到错误

但是现在我遇到打字稿编译错误 error TS2451: Cannot redeclare block-scoped variable 'Query'.

显然是因为打字稿无法将我的文件识别为模块。

因此,我尝试了this解决方案并将export {}添加到我的文件中,以便将它们识别为模块。但是因为我的目标是es2016我得到Unexpected token 'export'

有什么办法可以同时解决两个问题吗?

我的代码中都发生了错误,因此我将包含整个仓库:https://github.com/grochadc/filex-graphql-server

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016","moduleResolution": "node","outDir": "dist/","allowSyntheticDefaultImports": true
  },"include": ["src/"],"exclude": ["node_modules","**/*.spec.ts"]
}

解决方法

提取typescript docs

的相关部分

如果您具有以下Node / CommonJS代码:

var foo = require("foo");

foo.doStuff();

然后您将编写以下TypeScript代码:

import foo = require("foo");

foo.doStuff();

exporting

您以前可能是这样写的:

function foo() {
   // ... 
} 
module.exports = foo;

在TypeScript中,您可以使用export =构造模型。

function foo() {
  // ...
}
export = foo;

然后,如果您在tsconfig中设置"module": "CommonJS",它将把它们转换回现在的状态,这是一个传统的限制,即如果您没有导入或导出构造,它将假定它不是模块,因此您只需要使用importexport

将文件标记为模块