microsoft / microsoft/TypeScript

Allow narrowing of unions discriminated by numeric literals using `>` `<` etc

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

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

### 🔎 Search Terms

"arguments length"

### 🕗 Version & Regression Information

It works the same in v3.3.3

### ⏯ Playground Link

https://www.typescriptlang.org/play/?target=99&module=0&ts=5.8.3#code/GYVwdgxgLglg9mABAUwB4EMC2AHANsgRgAoA6M9AJwHMBnALkQG0wRMAjZCgXUQB8muASkQBvAFCJJiGMERFKtEvjBUoAC0QA+RAAZh4qYcQVkUEBSQKajHVwDcEqQF8UuGslGOjx0+aQA5dH8HQycxMNBIWAQUDBx8ACZScmp6JhZ2Th5+RiFPQxk5KyVkFXV9LyMTMwtEKxt7SpdkNw8Dbx8agKCQ53CxSOh4JDQsPGQAZmSSKwZmVg5uPgEKgtl5VJKyjQBePd1Vjuq-REDgptd3fKPfWvrbXskwpyA

### 💻 Code

Some basic ways to check if we have any arguments could be these:

```ts
function example1(...args: [number] | []) {
if (args.length > 0) {
return args[0];
} else {
return NaN;
}
}
function example2(...args: [number] | []) {
if (args.length) {
return args[0];
} else {
return NaN;
}
}
function example3(...args: [number] | []) {
if (args.length === 0) {
return NaN;
} else {
return args[0];
}
}
```

But TS doesn't seem to understand the first one.

### 🙁 Actual behavior

It doesn't understand the way it's done in "example1".

### 🙂 Expected behavior

It should understand the way it's done in "example1".

### Additional information about the issue

Type inference on "args" after the check for "example1":

![Image](https://github.com/user-attachments/assets/02538891-167b-459d-8fe8-ec966ad97990)

Type inference on "args" after the check for "example2":

![Image](https://github.com/user-attachments/assets/502573b5-346c-4eb9-9db6-89452c9f35b1)

Type inference on "args" after the check for "example3":

![Image](https://github.com/user-attachments/assets/aee70d26-b2b6-40c9-a9a0-555b0f914a55)

Notice how for "example2" and "example3" the type is correctly narrowed to just `[number]`, but for "example1" the unnarowed `[number] | []` type remains.

贡献指南

打开贡献指南

从这里开始

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

调研方向

以链接的 TypeScript Playground 示例作为入口点;将 args.length > 0 的控制流缩窄与现有的 truthiness 和 equality 情况进行比较。完成的标准是:example1 在 true 分支中将 [number] | [] 缩窄为 [number],同时不丢失 examples 2 和 3 所展示的行为。

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

评估

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

把新 issue 发到你的邮箱

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