流程可迭代式

问题描述 投票:1回答:1

我试图与添加到它的流动类型JavaScript来定义一个ZIP功能。

我对现在的类型有以下几种:

export function *zip<T>(...iterables:Array<Iterable<T>>): Iterable<Array<T>> {
   const iterators = iterables.map(iterable => iter(iterable));
   while(true){
      const items = iterators.map(iterator => iterator.next());
      if (items.some(item => item.done)){
         return;
      }
      yield items.map(item => item.value);
  }
}

function *iter<T>(iterable:Iterable<T>): Iterator<T> {
   yield* iterable;
}

错误流(0.64)给了我是在return;线和它说:

Generator
This type is incompatible with the expected return type of
$Iterable: tools/misc.js:182
Property `@@iterator` is incompatible:
function type: /private/tmp/flow/flowlib_38c3acbb/core.js:508
This type is incompatible with
function type: /private/tmp/flow/flowlib_38c3acbb/core.js:503

example in flow's documentation看起来非常相似,所以我不知道什么是错在这里。

关于类型的任何建议(甚至代码本身)也欢迎。

编辑的流量版本0.92.1是错误:

因为不确定的是房地产T的返回值的类型参数Yield的数组元素@@iterator不兼容无法返回undefined。

javascript flowtype
1个回答
2
投票

基于压缩发生器返回类型,其预期收益率类型Array<T>的值。然而,yield items.map(item => item.value);产生Array<void | T>,因为在该地图回调每个itemIteratorResult<T, void>。因此,有实际和预期收益率值之间的类型不匹配。

话虽这么说,你已经用你的检查项目:

if (items.some(item => item.done)){
   return;
}

,因此由时间执行到达yield没有项目值的可以是undefined。不幸的是流量不能弄清楚自身。但是,我们可以迫使它变成型铸造该值:

 export function *zip<T>(...iterables:Array<Iterable<T>>): Iterable<Array<T>> {
   const iterators = iterables.map(iterable => iter(iterable));
   while(true){
      const items = iterators.map(iterator => iterator.next());
      if (items.some(item => item.done)){
         return;
      }
      yield ((items.map(item => { return item.value }): Array<any>): Array<T>);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.