Skip to content

Narrowing the type inside forEach doesn't follow the if check from the outside #56854

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

https://www.typescriptlang.org/play?ssl=17&ssc=31&pln=17&pc=38#code/MYewdgzgLgBApgWwA5QJ4H0BOBXANnGAXhgAoIALOOKALhgGEBlZtfRy6gGhmFwEMIEdGD4I4daJgCWYAOYBKIgD4YAbwCwAKBg6e4aDBkATOAA8iMClSgA6YIIBKeOBBv45UcgG4tuyx1sZCDhMKCd8EgADGwASVV4BIRExAF81GBTI7mMzeR9tXUxqbEwwf2s7R2cIAG0c0wBdfJT8rVBIWGCodHsICzIAuiYWVDYA7gTBYVFxSyhpOW5oUdnGVjhFQhUNAp12g2D8YCgQTAtouMmkmcz8v3xYHHwLGps3q2pKiHCXBpsAM2MJCeBC2al8fkKxVKMBBhg6fDAwDgIH+DGYaxWPxgADIcbDnDZDnBjqcACpmWCEamWOBHE6YO66FJ5CE6KRokgAQhBih2kMKzgsiBQGBBA2sE34U2SGyZOhSbMMnLhQSgiORqPRI3wPz5Sr8+1g5mIIK5RPW8shAHkAEYAKxJtjgYHmUhcZHW8gBpwAonxgOQSCQakhMCAkNwAG58XDYOANTbbA0Cgn4C0rInUAAK4aQITQJDDEejsfjrN2kJZVr8dsdxxsLrdHuW+G9-z9AaDIeLkZgMbjCaT4MrqZgpizUFzEYLqCLedLg4rY+rSsVmhaQA

💻 Code

constempty_rule=(sheet: CSSStyleSheet,class_name: string)=>{constindex=sheet.cssRules.length;sheet.insertRule(`.${class_name} { }`,index);returnsheet.cssRules[index];};constset_css=(sheet: CSSStyleSheet,class_name: string,style: Style)=>{constselector=`.${class_name}`;letrule=[...sheet.cssRules].find(rule=>{returnruleinstanceofCSSStyleRule&&rule.selectorText===selector;});if(!rule){rule=empty_rule(sheet,class_name);}if(ruleinstanceofCSSStyleRule){constx=rule.style;Object.entries(style).forEach(([prop,value])=>{// this throw an errorrule.style.setProperty(prop,value);});Object.entries(style).forEach(([prop,value])=>{// this worksx.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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Possible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some cases

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions