Search code examples
typescriptapollo-datasource-rest

"Can't invoke class without new" and "Can't redeclare blocked-scoped variable" happening at the same time


I started having an error while trying to use RESTDataSource:

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

So I tried this solution and added "target": "es2016". I don't get the error anymore.

But now I'm getting typescript compilation error error TS2451: Cannot redeclare block-scoped variable 'Query'.

Apparently this is happening because typescript doesn't recognize my files as modules.

So I tried this solution and added export {} to my files so they get recognized as modules. But because my target is es2016 I get Unexpected token 'export'

Is there any way I can solve both problems at the same time?

The errors are happening all over my code so I will include the whole repo: 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"]
}


Solution

  • To pull out the relevant sections of the typescript docs

    If you had the following Node/CommonJS code:

    var foo = require("foo");
    
    foo.doStuff();
    

    then you would write the following TypeScript code:

    import foo = require("foo");
    
    foo.doStuff();
    

    and for exporting

    You might have previously written that like so:

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

    In TypeScript, you can model this with the export = construct.

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

    then if you set "module": "CommonJS" in your tsconfig it will translate these back to what you have now, this is a legacy limitation that if you don't have import or export constructs it assumes it is not a module, so you just need to label your files as modules by using import and export