microsoft / microsoft/TypeScript

Never-initialized variable type is not narrowed to undefined

未关闭
#61,496 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

### 🔎 Search Terms

narrow uninitialized, uninitialized undefined

### 🕗 Version & Regression Information

- This is the behavior in every version I tried, and I reviewed the FAQ for entries about `initialized`/`uninitialized`

### ⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.9.0-dev.20250326#code/MYewdgzgLgBAZiEMC8MAUUDuIBcNoBOAlmAOYCUeAbiEQCYoB8MA3gFAwwBEArhAKb4oxYFC4BuDjCkB6GTH4QANiSgBaOkQgBDAEZL+asPwAe6lcZgABKAE8ADouDF76xRagySRdXX7AlbQJtKCJwCCkDWHB+PEISUhgAHxgeMD84En46SSkiOHQYlGRULBByVilOORgAPQB+KpgagDlEeykAXzZutgQQNC4ucnEgA

### 💻 Code

```ts
const foo = (two: string): void => {
"use strict";

// eslint-disable-next-line @typescript-eslint/init-declarations
let one: string | undefined;

if (one === two) {
// ^? let one: string | undefined
// Noop
}
}

foo("");
```

### 🙁 Actual behavior

The type is not narrowed, which prevents typescript-eslint from flagging this comparison that always fails: [typescript-eslint playground](https://typescript-eslint.io/play/#ts=5.7.2&fileType=.tsx&code=MYewdgzgLgBAZiEMC8MAUUDuIBcNoBOAlmAOYCUeAbiEQCYoB8MA3gFAwwBEArhAKb4oxYFC4BuDjCkB6GTH4QANiSgBaOkQgBDAEZL%2BasPwAe6lcZgABKAE8ADouDF76xRagySRdXX7AlbQJtKCJwCCkDWHB%2BPEISUhgAHxgeMD84En46SSkiOHQYlGRULBByVilOORgAOUR7KQBfNha2BBA0Li5ycSA&eslintrc=N4KABGBECmAeAu0B2ATAzpAXGA2uCU0aANgJZLyYCGxxkANPhJAA7ECuA5uZgALwBPFkQDGAJ1It4AWiJkKAehp18AXUbMx7YkSxhQEAL4hDQA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false)

### 🙂 Expected behavior

The `one === two` comparison should be flagged because it always returns false (there is no way `one` has any value other than `undefined`).

### Additional information about the issue

Also filed a related issue with ESLint: https://github.com/eslint/eslint/issues/19581

贡献指南

打开贡献指南

调研方向

使用 TypeScript Playground 链接和 `one === two` 示例复现该行为,然后跟踪控制流 narrowing 如何处理从未初始化的变量。将结果与预期始终为 false 的比较进行对照,并使用链接的 ESLint issue 了解相关背景。完成的标准是:该比较被识别为不可能,同时不改变无关 narrowing 的行为。

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

评估

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

把新 issue 发到你的邮箱

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