#Control Flow Analysis

6 messages · Page 1 of 1 (latest)

ashen tundra
#

I'm fighting with typescript at a place where it's showing a control flow analysis based error.

while (foo === "apple") {
  changeFooToPear()
  while (foo === "pear") {
    makeFood()
    break
  }
}

I know that foo is changed to pear... so I'm fighting typescript. I'm here to ask, if typescript is trying to help me write better code, what is the clean solution?

eager scaffold
#

typescript kinda assumes functions are pure in this way, there's an issue for it somewhere

willow mason
#
let foo: "apple" | "pear" = "apple";
// Using a function avoids TS from 'remembering' the narrowed value
const getFoo = () => foo;

while (getFoo() === "apple") {
  changeFooToPear()
  while (getFoo() === "pear") {
    makeFood()
    break
  }
}
storm yacht
#

the easiest workaround is to not mutate/reassign anything ever 😏