gpt4 book ai didi

TypeScript 遍历元组数组

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:23 25 4
gpt4 key购买 nike

我如何在 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 的类型为 字符串 | number 尽管实际上它只能有类型 number?

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

最佳答案

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

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

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

Play

关于TypeScript 遍历元组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57528296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com