Issue
Here's (playground) some TypeScript:
let x: string | null = null;
[ 1 ].forEach(() => {
x = "hello";
});
if (x === null) {
throw new Error("unreachable");
}
console.log(x.length);
On the if
line, TS thinks x
has type null. This means that by the last line, x
has type never, and you get a type error.
Now, I know TS is conservative about code in closures. It can't assume that they will run and narrow types further or whatever. The thing that surprises me here is that TS seems to assume the code in the closure WON'T run, and x
will necessarily be unchanged by the map operation. This isn't conservative behavior at all. It seems bug-level mistaken to me.
So my questions are:
- Is there a good reason my desired behavior (assume that any closure passed into a function might be executed) isn't implemented in TypeScript?
- Is there some pattern I should use to get around this trouble?
Naturally, in my code I'm not just looping over [ 1 ]
; there's some kinda walker running in there.
Thanks in advance for any thoughts!
(For the record: this is all TypeScript 5.3.2.)
Solution
this is a known issue and is tracked by #9998 & 11498.
Basically, TS has no way to know that forEach
will be run instantly. It assumes that it is not ran. So the type is null
from inference.
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.