microsoft / microsoft/TypeScript
narrowing to "never" by "if" statement does not exclude "undefined" return type
未关闭
还没有人认领这个 Issue。
In Discussion
Suggestion
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.3k
- 平均合并
- 2 天 4 小时
- 30 天内合并 PR
- 132
描述
TypeScript Version: 2.7.1
Search Terms: narrowing types never switch case if undefined strictNullChecks
Code
// Build this code with "--strictNullChecks" option.
function assertNever(x: never): never {
throw new Error("not reached");
}
enum A {
Foo, Bar
}
// There are no errors on this function.
function good(a: A): number {
switch (a) {
case A.Foo: return 0;
case A.Bar: return 1;
}
}
// This function causes the following error though "a" is "never" at the end of the function.
// error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
function bad(a: A): number {
if (a === A.Foo) return 0;
if (a === A.Bar) return 1;
}
// No error if explicit return of "never" is added.
function ok(a: A): number {
if (a === A.Foo) return 0;
if (a === A.Bar) return 1;
return assertNever(a);
}
Expected behavior: The bad() function should not cause error so that if statement works like switch.
Actual behavior: As commented in the code, only bad() function causes an error.
Playground Link: (please check "strictNullChecks" option.)
Related Issues:
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先,在启用 strictNullChecks 的情况下复现 issue 的 TypeScript 代码,并比较 if 和 switch 分支。跟踪 compiler 对错误函数的控制流缩窄和缺少返回分析。当该案例中报告的 diagnostic 得到解决,且回归覆盖确认了该行为时,即视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 35/100