Issue with type narrowing in for loop.
Seeking solution for correct type narrowing implementation in for loop.
Provided below is a basic example (Please try running it on TS playground)
// uncertain whether string or null until runtime
const elements = [
{ textContent: Math.random() < 0.5 ? "test": null },
{ textContent: Math.random() < 0.5 ? "test": null },
{ textContent: Math.random() < 0.5 ? "test": null },
];
const data: {
content: string;
}[] = [];
// successful type narrowing
if (typeof elements[0].textContent === "string") {
data.push({ content: elements[0].textContent });
}
// unsuccessful type narrowing
for (const index in elements) {
if (elements[index].textContent && typeof elements[index].textContent === "string") {
data.push({
content: elements[index].textContent // <-- Error: Type 'null' is not assignable to type 'string'. textContent: string | null
});
}
}