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