microsoft / microsoft/TypeScript

Narrow number literal types with comparison

未关闭
#36,099 2 条评论 11 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Search Terms

constant number literals narrowing comparison

Suggestion

Narrow number literal type not only with (non)equality, but also with less-than etc.
This request is only about throwing away non-matching literals, and not about full-blown number narrowing.

Use Cases

This could be used to direct narrowing with tuple unions.

Examples

With literals

type X = 0 | 1 | 2 | 3;
function f(): X {
    return 1;
}
function g(x: 0 | 3) { 
    console.log(x);
}
let x: X = f();
g(x); // Error, 1 | 2 is unexpected
if (x > 2) { 
    g(x); // Same error, but should be safe
}
if (x != 1 && x != 2) { 
    g(x); // Ok
}

With tuples

type X = [] | [string, string];
function f(): X { return [];}
function g(x: string) { 
    console.log(x);
}
let x: X = f();
g(x[0]); // Error, undefined is unexpected
if (x.length > 0) { 
    g(x[0]); // Error, but should be ok
}
if (x.length == 2) { 
    g(x[0]); // Ok
}

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.

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 issue 中的字面量和元组示例开始,重现它们当前的诊断信息和 narrowing 行为。定义比较检查的预期控制流结果,包括小于比较和元组长度比较,并验证此更改只会移除不可能的字面量情况,而不会引入通用的数字 narrowing。

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

评估

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

把新 issue 发到你的邮箱

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