1

When I am developing in Typescript and I have a variable:

const fn: undefined | () => void

and write this:

...
if (!fn)
    return;
setTimeout(() => fn(), 0);
...

Typescript will complain, stating that the fn object could be undefined inside the setTimeout, as it is going to be executed asynchronously and by the time it does, the fn function might be indeed undefined and so it cannot be invoked as a function.

So I have to do something like this:

...
setTimeout(() => {
 if (!fn)
    return;
 fn();
}
, 0);
...

but at what level is the atomicity of statements achieved?

I mean even if I check that fn is not undefined in the if how can I be sure that it will still not be undefined by the statement fn(). At which level does javascript provide this "atomicity" / "concurrency"?

ZaO Lover
  • 433
  • 2
  • 13
but-why
  • 533
  • 3
  • 10
  • If you put the `setTimeout(() => fn(), 0);` into an `else` block, TS should stop complaining as you will be sure that `fn()` is defined when it is called be `setTimeout()` – secan Feb 17 '21 at 09:01
  • @secan Yes but why? Does it have to do with the call stack ? – but-why Feb 17 '21 at 09:02
  • I can't see typescript complaining in this little fiddle: https://www.typescriptlang.org/play?allowJs=true&target=6&ts=4.1.5#code/LAKAZgrgdgxgLgSwPZQARiUgFASlQb1FWNRhQGc500BeVXVGgPlIqQBsBTAOnaQHMsAIgAmKTkJwBuIiQRh6AQjBQcskiQBOnOBE1QZIdanI6AKggC2nJBDhYGzargA0qAAzTQAX1CgM2NJAA (unless I've got the TS settings wrong in the snippet?) – Nick Parsons Feb 17 '21 at 09:14
  • 1
    @NickParsons That's because you haven't stated that ```fn``` can also be undefined. Try this: ``` function foo() { let fn: undefined | (() => void) = () => console.log('not undefined'); if (!fn){ fn = undefined; return; } setTimeout(() => fn(), 0); } foo(); ``` – but-why Feb 17 '21 at 09:36
  • @but-why ah I see, thanks. If you watch the first 11min of [this](https://www.youtube.com/watch?v=cCOL7MC4Pl0&t=1036s&ab_channel=JSConf) video it might help you answer the atomicity part of your question – Nick Parsons Feb 17 '21 at 09:50

0 Answers0