【发布时间】: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