I
I
imp2021-11-06 09:33:29
JavaScript
imp, 2021-11-06 09:33:29

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);


The problem is that after the code is translated into JavaScript, the i and step variables begin to be interpreted as strings from the second iteration of the loop.
That is, this code writes to the console not 10 numbers (0, 10, 20 ... 90), as one might assume, but only two:
0, 010
- the first number (number), the second string (string) and ends the execution cycle.

How to make the variable i remain of type number?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-11-06
@bugsoff

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.
It is important to understand here that there will be nothing left of as in javascript, typescript will not generate type casting for you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question