My code:
JavaScript
x
13
13
1
function test() {
2
let value: number;
3
4
for (let i = 0; i < 10; i++) {
5
value = i;
6
console.log(value);
7
}
8
9
return value;
10
}
11
12
test();
13
And got this:
JavaScript
1
2
1
Variable 'value' is used before being assigned
2
I found this very odd, as I had seen other similar problems that either used a callback or a Promise or some other asynchronous method, while I used just a synchronous for loop.
———————————- Some update ————————
JavaScript
1
17
17
1
function test() {
2
let value: number;
3
4
for (let i = 0; i < 100; i++) {
5
// a() is very expensive and with some effects
6
const result = a(i)
7
8
if(i===99) {
9
value = result
10
}
11
12
}
13
14
return value;
15
}
16
17
Advertisement
Answer
Use the non-null assertion operator to ensure that “its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact.”
JavaScript
1
13
13
1
function test() {
2
let value!: number;
3
4
for (let i = 0; i < 10; i++) {
5
value = i;
6
console.log(value);
7
}
8
9
return value;
10
}
11
12
test();
13