【问题标题】:TypeScript loop over array of tuplesTypeScript 循环遍历元组数组
【发布时间】:2019-08-17 01:09:32
【问题描述】:

如何在 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

我认为https://github.com/microsoft/TypeScript/issues/3369 是使 TypeScript 无法推断出合适类型的问题。循环元组数组的当前解决方案是什么? Type assertions?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    真正的问题是[['a', 1], ['b', 2]] 的类型根本不是元组类型。它将是数组类型(string | number)[][]。所以当解构xy 时都将是string | number。 Typescript 只会在特定情况下推断元组(例如约束到数组的类型参数,或 as const 断言)。

    如果您使用as const 断言让打字稿推断元组类型,那么一切都会按预期工作:

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

    Play

    【讨论】:

    【解决方案2】:

    只需添加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);
    }
    

    【讨论】:

    • 回复:Map,假设 xs 是不同的。
    • 是的,这就是我基于 a,b,c 的假设
    猜你喜欢
    • 2020-11-24
    • 2021-08-27
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多