【发布时间】:2020-09-25 14:00:08
【问题描述】:
scenario.ts
export interface Step {
text: string;
image: string;
time: number
}
export interface IScenario {
name: string;
steps: Array<Step>;
}
餐厅.ts
import {IScenario, Step} from './interfaces/scenario'
export default class Restaurant implements IScenario {
name: string = 'Приключение в ресторане';
steps: Array<Step> = [
{
text: 'Вы пришли в ресторан',
image: 'https://sun9-3.userapi.com/55H3n5pt-TvwwdQzmpBZ9mcHURCqf85x1mXvlw/oyI4OlFu3R0.jpg',
time: 2000,
},
{
text: 'Перед вами стоит стол',
image: '',
time: 5000,
},
];
private *enumerateSteps(steps: Array<Step>): IterableIterator<Step> {
yield step;
}
start(): void {
for (const step of this.enumerateSteps(this.steps)) {
setTimeout(() => {
return console.log(step.text);
step.next();
}, step.time);
}
}
}
我想在 time 之后进行下一步,但出现错误:
类型“Step”上不存在属性“next”。
由于某种原因,我也有关于缺席step 的错误,但我不知道为什么。
【问题讨论】:
-
"由于某种原因缺少
step的错误" - 是的,您的enumerateSteps方法中没有定义step变量。你期望它是什么?请注意,您也没有在任何地方使用参数steps。 (但这似乎不是错字,因为它们有不同的类型)。 -
我想在每种情况下都得到礼物
step。我试图更新生成器const current = steps[0]; yield current;,但我仍然收到错误“属性'next'在类型'Step'上不存在: -
看起来您正在尝试异步迭代您的生成器。在这种情况下,正如@Bergi 所指出的,不需要一个,但该语言确实允许async interators。
-
Bergi 的回答非常好,但您的代码存在另一个问题 - 如果您在生成器函数中仅
yield一次(不在循环中),您只需迭代一次。换句话说,[...({ *[Symbol.iterator]() { yield 1 } })]就是[1]。 -
谢谢大家:)
标签: javascript typescript generator