Type is not referred correctly in the while loop
Author: mozesstumpfCreated Aug 22, 2024Updated Sep 16, 2026
LabelsBugHelp WantedDomain: check: Control Flow
Search Terms
incorrect type while loop
Version & Regression Information
Worked correctly in version 4.2.3. It doesn't work since 4.3.5.
⏯ Playground Link
Code
class Child extends HTMLElement {
get parent() {
const { parentElement } = this;
if (!(parentElement instanceof Parent)) {
return null;
}
return parentElement;
}
}
class Parent extends HTMLElement {
get parent() {
const { parentElement } = this;
if (!(parentElement instanceof GrandParent)) {
return null;
}
return parentElement;
}
}
class GrandParent extends HTMLElement {
get parent() {
const { parentElement } = this;
if (!(parentElement instanceof GreatGrandParent)) {
return null;
}
return parentElement;
}
}
class GreatGrandParent extends HTMLElement {
get parent() {
return null;
}
}
// irrelevant code
customElements.define("c-child", Child);
customElements.define("c-parent", Parent);
customElements.define("c-grand-parent", GrandParent);
customElements.define("c-great-grand-parent", GreatGrandParent);
type ParentElements = GreatGrandParent | GrandParent | Parent;
const child = new Child();
let currentParent: ParentElements | null = child.parent;
while (currentParent) {
console.log(currentParent); // should be GreatGrandParent | GrandParent | Parent
currentParent = currentParent.parent;
}
Actual behavior
The curerntParent's type is not referred correctly. It became Parent | GrandParent.
Expected behavior
The currentParent's type should be Parent | GrandParent | GreatGrandParent.
Additional information about the issue
No response
Source: microsoft/TypeScript