Microsoft/TypeScript
GitHub ã§èŠãNarrowed `const` variables are widened in block-scoped closures
Open
#61,158 opened on 2025幎2æ10æ¥
Domain: check: Control FlowHelp WantedPossible Improvement
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
ð Search Terms
narrowing, cfa, closure,
ð Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about n/a
⯠Playground Link
ð» Code
declare const s: string;
if (s === 'foo') {
function bad() {
const foo: 'foo' = s;
}
}
// in non-strict code bad() might be accessible outside of the narrowed branch,
// so make sure we're strict
export {}
ð Actual behavior
error trying to use the variable as its narrowed value.
ð Expected behavior
No error. bad() is a local function only reachable within the scope in which s has been definitely narrowed to 'foo'.
Additional Information
Found organically in https://github.com/typescript-eslint/typescript-eslint/pull/10182#discussion_r1948337564 (with a narrowed member access corollary)