Variable 'value' is used before being assigned
Asked Answered
G

3

5

My code:

function test() {
  let value: number;

  for (let i = 0; i < 10; i++) {
    value = i;
    console.log(value);
  }

  return value;
}

test();

And got this:

Variable 'value' is used before being assigned

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

function test() {
  let value: number;

  for (let i = 0; i < 100; i++) {
    // a() is very expensive and with some effects
    const result = a(i)

    if(i===99) {
      value = result
    }

  }

  return value;
}

Gold answered 19/11, 2021 at 2:59 Comment(1)
Typescript doesn't know that your the loop's body will be executed at-least once and the value variable will indeed be initialized. That is why you get the error. Assigning any initial value will fix the error.Callable
Q
11

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."

function test() {
  let value!: number;

  for (let i = 0; i < 10; i++) {
    value = i;
    console.log(value);
  }

  return value;
}

test();

Result

Quizmaster answered 19/11, 2021 at 3:4 Comment(1)
Nice! You can change the Result link to something like Online Demo.Pyelitis
N
2

TypeScript can't infer that anything in the loop body runs - it doesn't check that i starts at 0, and the condition is i < 10, and that the body will run at least once as a result. This behavior is very similar to the following:

function test() {
  let value: number;
  if (Math.random() < 0.5) {
    value = 5;
  }
  return value;
}

which produces the same error.

For TS to know that the value really definitely is defined at the end, you need to make it completely unambiguous. Usually, the best way this is achieved is by defining and assigning to the variable once, with const, through array methods and helper functions - TS works best when reassignment is minimized.

Nabors answered 19/11, 2021 at 3:5 Comment(6)
Thanks for the answer, but I didn't fully understand. Could you show me some code about your best way?Gold
It really depends on what exactly you're trying to do - there isn't enough context in the question as far as I can see to see what you're trying to do in the function, and why you're reassigning only inside the loop. 97% of the time, it's possible to refactor lets to consts (which will very often make TS happy as a result), but exactly how to refactor varies greatly.Nabors
The reason is that I have a very expensive calculation in for loop, and I want save some results in the last loop body, you could see the update part.Gold
For that code, to fix it, iterate from 0 to 98 instead of from 0 to 99, and then outside the loop, do return a(99).Nabors
Yes, it works in this situation, but how about a(50)?Gold
You could call that outside the loop and then use it / pass it around as needed.Nabors
A
0

I was facing this in typescript: Here was my solution that worked:

let myvariable: string | undefined;
if (typeof myvariable !== 'undefined') { 
    myvariable += "something appended"
} else {
    myvariable = "New beginning"
}
Allout answered 17/8, 2023 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.