Reputation: 1836
I have declared a for loop on an array of a specific type. When I use this array in for loop, I get error because typescript detects it as type of string rather than the type of specific item as declared.
const repos: Repo[] = config.get("repos");
for(const repo in repos) {
calculate(repo)
}
I get error that the value that I am passing to calculate is not of type Repo, but of type string.
NOTE: This is not a runtime error. I get it when in VS Code with code ts(2345)
Upvotes: 1
Views: 1400
Reputation: 84912
You likely meant to use a for ... of
loop, not a for ... in
loop. The code you've written loops over the enumerable keys of an object, so repo will start off as the string "0"
, then "1"
, etc. If instead you do for ... of
, you'll iterate through the array with repo being assigned the values in the array.
for(const repo of repos) {
calculate(repo)
}
Upvotes: 6