Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot find name 'AsyncIterator' error in Typescript compilation process. #83

Closed
ghost opened this issue Jun 29, 2017 · 54 comments
Closed

Comments

@ghost
Copy link

ghost commented Jun 29, 2017

I have found a difficulty compiling my Typescript code and it turns out that inside many files in graphql-subscriptions and subscriptions-transport-ws, the AsyncIterator iterator type interface is treated as defined, but the Typescript compiler doesn't agree with that. here is the list of errors:

node_modules/graphql-subscriptions/dist/pubsub-engine.d.ts(5,52): error TS2304: Cannot find name 'AsyncIterator'.
node_modules/graphql-subscriptions/dist/pubsub.d.ts(12,52): error TS2304: Cannot find name 'AsyncIterator'.
node_modules/graphql-subscriptions/dist/with-filter.d.ts(2,94): error TS2304: Cannot find name 'AsyncIterator'.
node_modules/graphql-subscriptions/dist/with-filter.d.ts(3,58): error TS2304: Cannot find name 'AsyncIterator'.
node_modules/subscriptions-transport-ws/dist/server.d.ts(5,41): error TS2304: Cannot find name 'AsyncIterator'.
node_modules/subscriptions-transport-ws/dist/server.d.ts(29,58): error TS2304: Cannot find name 'AsyncIterator'.
node_modules/subscriptions-transport-ws/dist/server.d.ts(32,31): error TS2304: Cannot find name 'AsyncIterator'.

screenshot 22

I had found a temporary solution to bypass the errors by defining AsyncIterator type interface in every file involved in node_modules, here is the definition:

interface AsyncIterator<T> {
  next(value?: any): Promise<IteratorResult<T>>;
  return?(value?: any): Promise<IteratorResult<T>>;
  throw?(e?: any): Promise<IteratorResult<T>>;
}

screenshot 23

@veeramarni
Copy link

Thanks for the workaround, I was having the same issue and adding the missing types have fixed the problem. But this is just a workaround, and it seems like those interfaces need to be in this project.

@veeramarni
Copy link

I think we can use esnext lib to fix this issue. See below link

#77

@ghost
Copy link
Author

ghost commented Jul 2, 2017

Thanks!!
By adding:

"compilerOptions": {
  "lib": [
     "esnext.asynciterable"
   ],
. . .

to tsconfig.json file fixed the issue for good.

@Parziphal
Copy link

If I add the lib array to compilerOptions, I get hundreds of errors because everything breaks (even Date becomes unavailable). Adding the interface to the files where the error occurs fixed the problem.

@comonadd
Copy link

comonadd commented Aug 9, 2017

@Parziphal, agree.

I think this problem is there because of the fact that TypeScript has the default "lib" option defined somewhere in the code.

So, in order to fix that problem, you need to include all of the libraries that "lib" option contains by default.
Those are:

"es5",
"es6",
"dom",
"es2015.core",
"es2015.collection",
"es2015.generator",
"es2015.iterable",
"es2015.promise",
"es2015.proxy",
"es2015.reflect",
"es2015.symbol",
"es2015.symbol.wellknown",
"esnext.asynciterable"

So, this solves the problem, - you just need to set the "lib" TypeScript compiler option to the array of default libraries concatenaed with the "esnext.asynciterable" library, like this:

{
  "compilerOptions": {
    // ...
    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015.core",
      "es2015.collection",
      "es2015.generator",
      "es2015.iterable",
      "es2015.promise",
      "es2015.proxy",
      "es2015.reflect",
      "es2015.symbol",
      "es2015.symbol.wellknown",
      "esnext.asynciterable"
    ]
  },
  // ...
}

@ghost
Copy link
Author

ghost commented Aug 9, 2017

But the problem is, you have to make that change after every npm install...

@joseluisq
Copy link

That works! 👍

@tal
Copy link

tal commented Aug 14, 2017

Hrm, adding the big list of options to lib didn't work for me. I got a bunch of other errors

node_modules/apollo-client/transport/afterware.d.ts(4,15): error TS2304: Cannot find name 'Response'.
node_modules/apollo-client/transport/afterware.d.ts(5,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/afterware.d.ts(11,16): error TS2304: Cannot find name 'Response'.
node_modules/apollo-client/transport/afterware.d.ts(12,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/batchedNetworkInterface.d.ts(8,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/batchedNetworkInterface.d.ts(11,16): error TS2304: Cannot find name 'Response'.
node_modules/apollo-client/transport/batchedNetworkInterface.d.ts(12,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/batchedNetworkInterface.d.ts(22,20): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/batchedNetworkInterface.d.ts(36,12): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/middleware.d.ts(5,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/middleware.d.ts(12,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/networkInterface.d.ts(35,12): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/networkInterface.d.ts(43,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/networkInterface.d.ts(46,15): error TS2304: Cannot find name 'Response'.
node_modules/apollo-client/transport/networkInterface.d.ts(47,14): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/networkInterface.d.ts(54,12): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/networkInterface.d.ts(55,49): error TS2304: Cannot find name 'RequestInit'.
node_modules/apollo-client/transport/networkInterface.d.ts(63,77): error TS2304: Cannot find name 'Response'.
node_modules/apollo-client/transport/networkInterface.d.ts(70,12): error TS2304: Cannot find name 'RequestInit'.

@comonadd
Copy link

comonadd commented Aug 15, 2017

I should also note that the default library list changes when compilerOptions.target gets changed.

So, you should probably go here, find --lib option, and look at the defaults which fit your needs.

@daniele-zurico
Copy link

Hi guys I'm having the same problem:
ERROR in /Users/danielezurico/Downloads/angular-graphql-master/quickstart-with-apollo/node_modules/@types/graphql/subscription/subscribe.d.ts (17,4): Cannot find name 'AsyncIterator'. ERROR in /Users/danielezurico/Downloads/angular-graphql-master/quickstart-with-apollo/node_modules/@types/graphql/subscription/subscribe.d.ts (29,4): Cannot find name 'AsyncIterable'.

I tried to add
"lib": [ "es5", "es6", "dom", "es2015.core", "es2015.collection", "es2015.generator", "es2015.iterable", "es2015.promise", "es2015.proxy", "es2015.reflect", "es2015.symbol", "es2015.symbol.wellknown", "esnext.asynciterable" ]
my package.json is:
https://github.com/graphcool-examples/angular-graphql/blob/master/quickstart-with-apollo/package.json

@ErbolLab
Copy link

ErbolLab commented Sep 1, 2017

I also faced with the same issue:

adding "esnext" to the "lib" fixed my problem.
"lib": ["es6", "dom", "esnext"],

https://github.com/graphcool-examples/angular-graphql/pull/8/files

@adrianmoya
Copy link

I also hit this issue twice. The first time adding the extra libs worked. The second time it didn't. I'm trying to run this example https://github.com/scaphold-io/angular4-apollo-client-starter-kit but no luck with the workaround. Is this going to be fixed in some way?

@mpicard
Copy link

mpicard commented Sep 11, 2017

This has become a major annoyance for me as well, having 'fixed' it a while ago but now it seems to be an issue again and no combination of "lib": [...] seems to work now

@flosky
Copy link

flosky commented Sep 12, 2017

+1 for major annoyance!

@flosky
Copy link

flosky commented Sep 23, 2017

This is becoming a real blocker now!

I have added the lib stuff to the tsconfig.json and it compiles without error. But now I am loading another module via package.json that we have written ourselves (which compiles itself without errors) and it breaks the npm install with the same AsyncIterator Error.

So each projects compiles without errors, but when I import the other project then the build fails. What is going on here?

Is there a fix on the way? It's been a couple of months now

@ghost
Copy link
Author

ghost commented Sep 23, 2017

@flosky: could you be more specific with some code snippets maybe I can help..

@flosky
Copy link

flosky commented Sep 25, 2017

Sure, thanks for the help.

My main project uses the serverless package, which also includes the graphql types. I am not actually using them, thats why this is even more frustrating. I was running into the error when trying to transpile my code. I then followed the workaround suggestions and it worked. Here is the tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitAny": false,
    "removeComments": true,
    "preserveConstEnums": true,
    "outDir": "build",
    "allowJs": true,
    "target": "es2015",
    "sourceMap": true,
    "baseUrl": "./",
    "paths": {
      "*": [ "node_modules/@types/*", "*"]
    },
    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015.core",
      "es2015.collection",
      "es2015.generator",
      "es2015.iterable",
      "es2015.promise",
      "es2015.proxy",
      "es2015.reflect",
      "es2015.symbol",
      "es2015.symbol.wellknown",
      "esnext.asynciterable"
    ]
  },
  "exclude": [
    "node_modules",
    "coverage",
    "build",
    ".git"
  ]
}

I also have another project (a logger module) that I would like to include into my main project. It is not affected by the bug here. I add the dependency to my my main projects package.json as a git link, like this:

"logger": "git+https://<secret>[email protected]/xyz/logger.git#1.1.1"

the logger module runs tsc on postinstall. Now when I run npm install on my main project, I get this error message:

> [email protected] postinstall /Users/flo/Workspace/stockLoader/node_modules/spawn-sync
> node postinstall


> [email protected] postinstall /Users/flo/Workspace/stockLoader/node_modules/logger
> tsc lib/index.ts --outDir build/lib -d --pretty


17 ): AsyncIterator<ExecutionResult>;
      ~~~~~~~~~~~~~

../@types/graphql/subscription/subscribe.d.ts(17,4): error TS2304: Cannot find name 'AsyncIterator'.

/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:2062
            throw e;
            ^

Error: Debug Failure. False expression.
    at computePositionOfLineAndCharacter (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:3752:22)
    at Object.getPositionOfLineAndCharacter (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:3742:16)
    at Object.formatDiagnosticsWithColorAndContext (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:55575:59)
    at reportDiagnosticWithColorAndContext (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:58771:25)
    at reportDiagnostic (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:58733:9)
    at reportDiagnostics (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:58738:13)
    at compileProgram (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:59099:13)
    at compile (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:59051:26)
    at performCompilation (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:58940:33)
    at Object.executeCommandLine (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:58883:9)
    at Object.<anonymous> (/Users/flo/Workspace/stockLoader/node_modules/typescript/lib/tsc.js:59241:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/flo/Workspace/stockLoader/node_modules/typescript/bin/tsc:2:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

When I transpile the logger module directly, in its own repo then it works without problems. I only get this error when I reference the dependency in my main project.

@ghost
Copy link
Author

ghost commented Sep 25, 2017

@flosky did you add "esnext.asynciterable" to the "lib" attribute in ts.config file of logger module?

@flosky
Copy link

flosky commented Sep 25, 2017

@ibraback Yes, I have. At first I removed it and it also worked as it is not using any types from graphql. But I have also added it again (the tsconfig.json is the same as I posted above), pushed the tag again, referenced the new tag in my main project, ran npm install again but same error

@ghost
Copy link
Author

ghost commented Sep 25, 2017

@flosky try to add --lib esnext.asynciterable parameter to the tsc lib/index.ts --outDir build/lib -d --pretty command.

@flosky
Copy link

flosky commented Sep 27, 2017

@ibraback thanks it sort of worked. I had to add some more libs to make it work. This is my code: "postinstall": "tsc lib/index.ts --outDir build/lib -d --pretty --lib es2015,dom,esnext.asynciterable",.

But what is the timeline to have this fixed?

@ghost
Copy link
Author

ghost commented Sep 27, 2017

@flosky since adding esnext.asynciterable to tsconfig file fixed the problem for the majority I don't think there is something to add/fix, but always upgrade your dependencies just in case...

@leebenson
Copy link

leebenson commented Oct 27, 2017

FWIW, the only fix that worked for me was this exact tsconfig.json:

TL;DR: the only thing in lib is esnext -- esnext.asynciterable alone yielded the following error:

error TS2318: Cannot find global type 'Boolean'.
error TS2318: Cannot find global type 'Function'.
error TS2318: Cannot find global type 'Number'.
error TS2318: Cannot find global type 'Object'.
error TS2318: Cannot find global type 'RegExp'.

{
  "compilerOptions": {
    /* Basic Options */
    "target": "ES2017",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": [                                  /* Specify library files to be included in the compilation:  */
      "esnext"
    ],                             
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                            /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    "noUnusedLocals": true,                /* Report errors on unused locals. */
    "noUnusedParameters": true            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

@schmidsi
Copy link

I had the same problem and the following change to tsconfig.json did the trick:

  • Add skipLibCheck: true to compilerOptions

Example tsconfig.json:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "skipLibCheck": true,
    "jsx": "react"
  },
  "include": [
    "./src/**/*"
  ],
  "lib": [
    "esnext",
  ],
}

@charlieg-nuco
Copy link

I'm just getting started with typescript and I got this issue. Only I was missing AsyncIterable as well. Adding that interface gets rid of the compilation error but there has to be a more elegant fix.

@niba
Copy link

niba commented Aug 5, 2018

@schmidsi your config file has the error, lib should be inside compilerOptions. The correct configuration is

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "skipLibCheck": true,
    "jsx": "react",
    "lib": [
       "esnext",
     ],
  },
  "include": [
    "./src/**/*"
  ],
 
}

Probably after this fix you don't need to set the skipLibCheck to true anymore

southpolesteve added a commit to Azure/azure-cosmos-js that referenced this issue Sep 19, 2018
Fixes #127. I'm not exactly sure why this is necessary, but seeing reports of a similar issue in another lib apollographql/graphql-subscriptions#83
@Morphexe
Copy link

Morphexe commented Nov 4, 2018

None of the solutions work :)
Adding EsNext does nothing for me, throws the error on browser.

@grantwwu
Copy link
Contributor

grantwwu commented Nov 5, 2018

Can you post your tsconfig.json?

@brianschardt
Copy link

same issue as Morphexe heres my file
{
"compilerOptions": {
"target": "es6",
"lib": [
"es5",
"es6",
"dom",
"es2015.core",
"es2015.collection",
"es2015.generator",
"es2015.iterable",
"es2015.promise",
"es2015.proxy",
"es2015.reflect",
"es2015.symbol",
"es2015.symbol.wellknown",
"esnext.asynciterable"
],
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": false,
"outDir": "dist",
"typeRoots": ["node_modules/@types"]
},
"files": ["src/app.ts"],
"exclude": ["node_modules"]
}

@grantwwu
Copy link
Contributor

grantwwu commented Dec 6, 2018

Try
"esModuleInterop": true as an entry in compilerOptions

@brianschardt
Copy link

@grantwwu thanks for the quick response. Tried that did not work
Here is the repo I want to run
tsc src/app.ts

https://github.com/brianalois/node_graphql_apollo_template

@grantwwu
Copy link
Contributor

grantwwu commented Dec 6, 2018

I believe that if you try to compile a particular file, it does not use your tsconfig.json. Try just running tsc at the root of your project. I was able to compile it fine there, after npm install --save-dev @graphql/types

@switch120
Copy link

Holy crap ... @grantwwu that was the fix for me too; just don't specify a .ts file. I would never have just tried that. Ugh!

@zgldh
Copy link

zgldh commented Apr 15, 2019

// Polyfill Symbol.asyncIterator
(Symbol as any).asyncIterator = Symbol.asyncIterator || Symbol("Symbol.asyncIterator");

https://stackoverflow.com/questions/43258568/for-await-of-simple-example-typescript

@ilyaskarim
Copy link

Installing Graphql types solved my case:

npm install --save-dev @types/graphql

@akomm
Copy link

akomm commented Nov 18, 2019

Note that there is a small risk with using "esnext" instead of "esnext.asynciterable" specifically: "esnext" will allow you to use any new JS features supported by TypeScript regardless of whether or not you have a polyfill for them. So be mindful of which ES2016+ features you're using and use something like https://polyfill.io if you want broad browser support.

The only sane reply here. The question is, whether the graphql library uses the feature or just produces a polyfilled fake of the interface. If the later is the case, adding es2018.asynciterable or esnext.asynciterable to lib in tsconfig.json is okay. If the former is the case, you need to polyfill the feature.

@mbrowne
Copy link

mbrowne commented Nov 19, 2019

@akomm Looking back on my earlier comment, I'm not sure why I was thinking about browsers at the time, since this library is primarily used in node.js (although I did find one client-side library, graphql-genie-client, for which graphql-subscriptions is a dependency, but I don't think it's very widely used). But as far as I can tell, full support of async iterators isn't needed (probably thanks to this library's use of the iterall library)—it's only a TypeScript issue. If I recall correctly, I successfully ran graphql-subscriptions on node 8 in the past (and the @types/node version seems to indicate it's compatible with node 8). BTW, async iterators are supported natively in node 10+.

@akomm
Copy link

akomm commented Nov 19, 2019

Yes. Since 10.3.0 it seems.

@OmgImAlexis
Copy link
Contributor

Possibly related leebyron/iterall#49

@stephengtuggy
Copy link

This thread seems to be filled mostly with different ways to disable or get around TypeScript's type safety checking. Why anyone would want to do that is beyond me. Type safety checking is there for a reason, you guys. It tells you when you're making a mistake. Or when there's an unexpected compatibility issue.

In my case, it told me that graphql-subscriptions v3 doesn't support asyncIterator like v2 did. I think asyncIterableIterator may be a suitable replacement? Someone correct me if I'm wrong on that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests