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": "^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];
}
}
推荐阅读
- r - 在列表中的每个位置中包含已存在的元素
- sql-server - SQL Server 错误:“'xyz' 附近的语法不正确”
- java - Kotlin:为 guice 注入的依赖项添加一个接口,以便我们可以模拟它们仅用于单元测试目的?
- java - 控制批量 api ElasticSearch 的超时
- python - 通过运行函数设置变量
- java - 未经许可的 iTextPdf setEncryption
- python - Python没有结果和KeyError:1
- c++ - 连接到远程存储库并获取数据
- postgresql - Postgres 中是否有 varchar 字段的 diff/patch 函数/库
- javascript - 复制要在 JavaScript 中迭代的 div 的最佳方法是什么?