Search code examples
typescriptundefined

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


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?


Solution

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