Infer const-ness of local let bindings that aren't assigned to

未关闭
#39,251 9 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
35/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
停滞
技术栈
typescript
领域
compilers

调研方向

从提供的 foo 示例开始,将提议的 local-let 行为与 const 绑定和函数参数的现有行为进行比较。将补全定义为:当局部 let 绑定没有任何赋值时,在闭包 callback 内保留收窄后的类型;当它可能被修改时,保留现有行为;为这两种情况添加覆盖。

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

描述

Awaiting More Feedback Suggestion

Search Terms

let const infer assignment

Suggestion

In some cases, type narrowing for const bindings is more effective than for let bindings. Specifically, using such bindings from a function that closes over them will keep the narrowed type, which doesn't happen for let binding, presumably on the assumption that those might be mutated at any time.

This suggests to treat local let bindings that are never assigned to (which can be determined by a rather straightforward static check on the syntax tree) like const bindings for this purpose.

(Interestingly, something like this seems to already exist for function parameters.)

Use Cases

Though some people have adopted a coding style where locals are declared with const unless assigned to, there's also a good argument to be made that that is not a very good use of brain cycles and just using let for all locals is fine. This proposal would improve type inference for people using the let style.

Examples

function foo() {
  let v: number[] | null = Math.random() < 0.5 ? [1] : null
  if (Array.isArray(v)) setTimeout(() => console.log(v.length), 100)
}

The compiler complains that v is possibly null. If the binding is changed to const the problem goes away. If v is made a function parameter it also doesn't occur. (But comes back when a v = null statement is added, suggesting a check like the one suggested here is being done in that case.)

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.
主要语言
Go
星标
111k
派生
14.4k
平均合并
1 天 19 小时
30 天内合并 PR
117

贡献指南

打开贡献指南

从这里开始

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

microsoft/TypeScript 的其他 Issue

查看 microsoft/TypeScript 的全部 Issue

相似的 Issue

更多 Go Issue

把新 issue 发到你的邮箱

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