When you try to set a variable inside a forEach
callback function in TypeScript, you may encounter issues with the variable's type. Here's a simple example:
let foo: (string | null) = null;
[1,2,3].forEach((i) => {
foo = "bar";
});
if(foo == null) {
throw new Error("not found")
}
# Typescript complains that `length` is not a property of type `never`
console.log(foo.length)
After the forEach
loop, you might expect foo
to have the type string | null
, but it actually ends up being just null
. Then, by the time you reach the console.log
line, you would anticipate the type to be string
, but TypeScript infers it as never
, since null
has been eliminated as a possibility due to the earlier Error
throwing.
Interestingly, the same code without specifying : (string | null)
works fine in plain JavaScript, highlighting a discrepancy between my expectations and the behavior of the TypeScript compiler.
So here are my queries:
- I'm looking for an explanation as to why this occurs so I can enhance my understanding of TypeScript.
- What is the best way to resolve this issue? Is there a better approach than using
foo = foo as string
before theconsole.log
statement?