Closed
Description
π Search Terms
type narrowing
π Version & Regression Information
- I was unable to test this on prior versions because I was testing in the playground
β― Playground Link
π» Code
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);
});
}
};
π Actual behavior
You can't use a variable that was type narrowed inside forEach. You got an error:
Property 'style' does not exist on type 'CSSRule'.
π Expected behavior
I expect rule.style
to work the same inside map.
Additional information about the issue
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.