Home > OS >  Condition in while loop, how to avoid TS2532: Object is possibly 'undefined'
Condition in while loop, how to avoid TS2532: Object is possibly 'undefined'

Time:07-08

Consider the following snippet:

let f = function(): number | undefined {
    return 1;
}

while (f() > 1) {
    console.log('hi');
}

It has an issue that f can return undefined. Let's fix it:

while (f() && f() > 1) {
    console.log('hi');
}

Does not pass the typecheker, gives me TS2532. How do I need to modify the condition in the while loop?

CodePudding user response:

The return value can be number | undefined. This does not mean that the function will return the same type of value when called twice in a row. (What if the type returned depends on a flag that gets toggled every call, or depends on Math.random?)

Try assigning the result to a variable and checking that variable.

while (true) {
  const result = f();
  if (!result || result <= 1) {
    break;
  }
  console.log('hi');
  // more code here if desired
}
  • Related