microsoft / microsoft/TypeScript

Narrowed `const` variables are widened in block-scoped closures

未关闭
#61,158 2 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Domain: check: Control Flow Help Wanted Possible Improvement
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

🔎 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

https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true&target=99&ts=5.8.0-dev.20250209#code/CYUwxgNghgTiAEYD2A7AzgF3mgXNjMAligOYDcAUBYQGbwAUa8AvK-AOQ1JLsCU8AbwrwRiVJmwBBCIShNm2SqPg0ArijAZCqeACMowevyHLlydFi5I8nbuxaLhogL5VlajVp0luh409MxCxVuGyt7BTRpWTQlFwpXChAADwAHJBgsAWcgA

💻 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)

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从链接的 TypeScript Playground 复现示例以及展示块作用域函数中经过缩窄的 const 的代码示例开始。追踪局部函数声明的控制流缩窄处理方式,并验证该示例不再报告错误,同时保留 issue 中描述的 strict-mode 行为。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。