Typescript - 在数组的 for 循环中对字符串进行类型更改

Adi*_*iri 1 types typescript

我已经在特定类型的数组上声明了 for 循环。当我在 for 循环中使用这个数组时,我收到错误,因为打字稿将其检测为字符串类型,而不是声明的特定项目的类型。

const repos: Repo[] = config.get("repos");
for(const repo in repos) {
  calculate(repo)
}
Run Code Online (Sandbox Code Playgroud)

我收到错误消息,我传递给计算的值不是 Repo 类型,而是 string 类型。

注意:这不是运行时错误。我在 VS Code 中使用代码 ts(2345) 时得到它

Nic*_*wer 5

您可能想使用for ... of循环,而不是for ... in循环。您编写的代码会遍历对象的可枚举键,因此 repo 将以 string "0"、 then"1"等开始。如果您这样做for ... of,您将迭代数组,并为 repo 分配数组中的值。

for(const repo of repos) {
  calculate(repo)
}
Run Code Online (Sandbox Code Playgroud)