Typescript不能识别yield关键字在生成器函数或生成器体中



这是我的生成器函数:

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

这是检查错误:

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

typescript期望什么?

附加信息:

<打印稿版本/em>

"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"
]
}

无法识别yield的原因是您在非生成器函数中调用了yield。重要的是要意识到您不能在此函数中调用yield。

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

而是在这个函数中调用yield

(num) => {

}

因为这个函数不是一个生成器函数,所以你会得到这个错误。

要解决这个问题,可以使用循环而不是数组迭代器函数。

代码应该是这样的

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

最新更新