【发布时间】:2021-10-26 22:08:26
【问题描述】:
这是我的生成器函数:
function* generatorFunction(input: number[]): IterableIterator<number> {
input.forEach((num) => {
yield num;
});
这是 linting 错误:
A 'yield' expression is only allowed in a generator body.ts(1163)
打字稿期待什么?
其他信息:
Typescript 版本
"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"
]
}
【问题讨论】:
-
那是 not 在生成器主体中,它在(非生成器)回调中。
-
你试过
function* generatorFunction(input: number[]): Generator { ... }吗? -
@SethLutske 是的,我尝试将
IterableIterator<number>替换为Generator,但仍然出现错误。 -
这就是你想要产生的价值,但在语法上它不能。所以你需要考虑另一种循环方式。
-
在生成器中使用
while循环很常见,这可能会成功
标签: typescript generator yield