1

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)

1 Answer 1

6

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.