TypeScript 循环元组数组

2024-05-13

如何在 TypeScript 中循环元组数组?例如

for (const [x, y] of [['a', 1], ['b', 2]]) {
  y + 1;
}

抱怨:

error TS2365: Operator '+' cannot be applied to types 'string | number' and '1'.

如果我理解正确的话,TypeScript 会推断类型(string | number)[][]对于循环表达式,这就是为什么循环变量y有类型string | number虽然实际上它只能有类型number?

I think https://github.com/microsoft/TypeScript/issues/3369 https://github.com/microsoft/TypeScript/issues/3369是导致 TypeScript 无法推断出合适类型的问题。循环元组数组的当前解决方案是什么?类型断言 https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions?


只需添加 TS 应该理解结构的类型注释即可。它还不能从集合中推断出来。

const array: [string, number][] = [['a', 1], ['b', 2]];

for (const [x, y] of array) {
  y + 1;
}

另外我想提一下,在处理二维关联时,我认为更好的数据结构是 Map:

const myMap = new Map<string, number>([['a', 1], ['b', 2]]);

for (const [x, y] of [...myMap]) {
  console.log(y + 1);
}

高级:自定义迭代

如果元组的逻辑是一致的,那么您可以使用以下方法创建自己的可迭代对象Symbol.iterator著名符号:

class TupleMaker implements Iterable<[string, number]> {
  private next = 0;
  constructor(private endsAt: number = 0) {}

  private increment(): void {
    this.next++;
  }

  *[Symbol.iterator](): Generator<[string, number]> {
    const alpha = Array.from(Array(26)).map((e, i) => i + 65);
    const alphabet = alpha.map((x) => String.fromCharCode(x).toLocaleLowerCase());
    while (this.next < this.endsAt) {
      yield [alphabet[this.next], this.next + 1];
      this.increment();
    }
  }
}

for (const [x, y] of new TupleMaker(13)) {
  console.log(y + 1);
}

它们也可以是异步的,使用Symbol.asyncIterator

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript 循环元组数组 的相关文章

随机推荐