Search code examples
typescriptgeneratoryield

Typescript not recognizing that yield keyword is in a generator function or generator body


This is my generator function:

function* generatorFunction(input: number[]): IterableIterator<number> {
  input.forEach((num) => {
    yield num;
  });

This is the linting error:

A 'yield' expression is only allowed in a generator body.ts(1163)

What is typescript expecting?

Additional info:

Typescript versions

"typescript": "^4.2.3"
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "strict": true,
    "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
    "strictNullChecks": true /* Enable strict null checks. */,
    "strictFunctionTypes": true /* Enable strict checking of function types. */,
    "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. */,
    "importHelpers": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "outDir": "./dist/tsc/",
    "types": [
      "node",
      "jest"
    ],
    "lib": [
      "ES6",
      "DOM"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts"
  ]
}


Solution

  • The reason yield is not recognized is because you are calling yield inside a non generator function. It is important to realize you are not calling yield within this function.

    function* generatorFunction(input: number[]): IterableIterator<number> {
     }
    

    But rather calling yield inside this function

    (num) => {
       
    }
    

    Since this function is not a generator function you are getting that error.

    To fix this use a loop instead of an array iterator function.

    The code should look something like this instead

    function* generatorFunction(input: number[]): IterableIterator<number> {
      for(let i = 0; i < input.length; i++){
         yield input[i];
      }
    }