【问题标题】:TypeScript - possibly undefined compilation error when throwing by iteratorTypeScript - 迭代器抛出时可能出现未定义的编译错误
【发布时间】:2017-08-18 00:51:19
【问题描述】:

当令人讨厌的转译器行为发生时,我正在使用生成器继续训练 ts。当然,我使用--strictNullChecks

function* generat(end: number) {
  for (let i = 0; i <= end; i++) {
    try {
      yield i;
    } catch (e) {
      console.log(e);
    }
  }
}

let iterat = generat(5);

console.log(iterat.next());
console.log(iterat.next());
console.log(iterat.throw()); // error: Object is possibly 'undefined'.
console.log(iterat.next());
console.log(iterat.next());
console.log(iterat.next());

有人知道聪明的解决方案吗?我的意思是聪明的东西不同于这个链接:https://github.com/Microsoft/TypeScript/issues/14431

【问题讨论】:

    标签: typescript iterator undefined generator throw


    【解决方案1】:

    很遗憾,throw and return are both optional in Iterator

    interface Iterator<T> {
      next(value?: any): IteratorResult<T>;
      return?(value?: any): IteratorResult<T>;
      throw?(e?: any): IteratorResult<T>;
    }
    

    老实说,我不明白为什么生成器必须返回迭代器而不是更具体的东西。毕竟,GeneratorFunctions 总是返回一些东西,而且它们总是会出错。 I filed a suggestion for TypeScript here.

    与此同时,您可以通过以下方式解决此问题:

    iterat.throw!()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多