Microsoft/TypeScript
Narrowed `const` variables are widened in block-scoped closures
開放
#61,158 建立於 2025年2月10日
Domain: check: Control FlowHelp WantedPossible Improvement
倉庫指標
- 星標
- (108,860 顆星)
- PR 合併指標
- (PR 指標待抓取)
描述
🔎 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)