Answer the question
In order to leave comments, you need to log in
Why does JavaScript interpret the loop variable as being of type string?
I write in TypeScript.
There is a function, the step of the inner for loop is passed to it in the parameters, like this:
function loop(step: number) {
for (let i:number = 0; i < 100; i += step as number)
console.log(i);
}
loop(10);
Answer the question
In order to leave comments, you need to log in
You don't need to explicitly write types where typescript can infer them. And even more so, you need to avoid type casting through as:
function loop(step: number) {
for (let i = 0; i < 100; i += step)
console.log(i);
}
There is no error in this code, the error is elsewhere. Typescript doesn't change the logic in the output javascript at all. I would look for other places where you call this function. Somewhere you pass a string into it, convincing typescript via the as operator that it is a number. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question