Reputation: 1
For the below code,
// Print indexes
var randArray = [5, 6, 7, 8];
for(var val in randArray){ // val is type inferred to String type
document.write(val + "<br>");
}
// Print values
for(var val of randArray){ // Line 95
document.write(val + "<br>");
}
Below is the error,
tstut.ts(95,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'val' must be of type 'string', but here has type 'number'.
Below code,
// Print indexes
var randArray = [5, 6, 7, 8];
for(var index in randArray){
document.write(index + "<br>");
}
// Print values
for(var val of randArray){
document.write(val + "<br>");
}
resolves the problem.
In problem case, Why val
type cannot be number
type?
Upvotes: 0
Views: 1338
Reputation: 1
Using "for..in" in JavaScript exposes the key/index of an array , simply 'coz it doesn't iterate over array items, instead it iterates over the keys/index in an array. For example,
var randArray = [5, 6, 7, 8];
for(let val in randArray){
document.write(val + "<br>");
}
In above code, no matter what items does "randArray" array contains its always going to throw the indexes.
"for..of" comes to the rescue. This is one of the reasons why "for..of" exists in TypeScript (and ES6). The above code with "for..of" loop will iterate over items in an array.
Also, replace "var" with "let" 'coz "let" keyword binds the variable to the local scope unlike "var" keyword in JavaScript.
Upvotes: 0
Reputation: 3082
An easy fix to your code is to change var
to let
:
// Print indexes
var randArray = [5, 6, 7, 8];
for(let val in randArray){
console.log(val);
}
// Print values
for(let val of randArray){
console.log(val);
}
Your problem has it's root in how var
keyword scopes the variable. (See the manual.) var
declarations' scope is the enclosing functions, thus your second for(var val...)
point in fact to the same variable and in TypeScript, they have a single, defined type. let
instead scopes the variable in to the enclosing block or for
, which means that the two variables can have same name, but are still separate variables.
Upvotes: 3