Narrowing the type inside forEach doesn't follow the if check from the outside · Issue #56854 · microsoft/TypeScript (original) (raw)
const empty_rule = (sheet: CSSStyleSheet, class_name: string) => {
const index = sheet.cssRules.length;
sheet.insertRule(.${class_name} { }
, index);
return sheet.cssRules[index];
};
const set_css = (sheet: CSSStyleSheet, class_name: string, style: Style) => {
const selector = .${class_name}
;
let rule = [...sheet.cssRules].find(rule => {
return rule instanceof CSSStyleRule && rule.selectorText === selector;
});
if (!rule) {
rule = empty_rule(sheet, class_name);
}
if (rule instanceof CSSStyleRule) {
const x = rule.style;
Object.entries(style).forEach(([prop, value]) => {
// this throw an error
rule.style.setProperty(prop, value);
});
Object.entries(style).forEach(([prop, value]) => {
// this works
x.setProperty(prop, value);
});
}
};
You can't use a variable that was type narrowed inside forEach. You got an error:
I expect rule.style
to work the same inside map.
It looks like inside forEach all typechecks are ignored. Another issue is that the rule
can be undefined inside forEach
but outside it's ok.