microsoft / microsoft/TypeScript

narrowing to "never" by "if" statement does not exclude "undefined" return type

未关闭
#21,985 3 条评论 28 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 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.)

http://www.typescriptlang.org/play/#src=function%20assertNever(x%3A%20never)%3A%20never%20%7B%0D%0A%20%20%20%20throw%20new%20Error(%22unexpected%22)%3B%0D%0A%7D%0D%0A%0D%0Aenum%20A%20%7B%0D%0A%20%20%20%20Foo%2C%20Bar%0D%0A%7D%0D%0A%0D%0Afunction%20good(a%3A%20A)%3A%20number%20%7B%0D%0A%20%20%20%20switch%20(a)%20%7B%0D%0A%20%20%20%20%20%20%20%20case%20A.Foo%3A%20return%200%3B%0D%0A%20%20%20%20%20%20%20%20case%20A.Bar%3A%20return%201%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Afunction%20bad(a%3A%20A)%3A%20number%20%7B%0D%0A%20%20%20%20if%20(a%20%3D%3D%3D%20A.Foo)%20return%200%3B%0D%0A%20%20%20%20if%20(a%20%3D%3D%3D%20A.Bar)%20return%201%3B%0D%0A%7D%0D%0A%0D%0Afunction%20ok(a%3A%20A)%3A%20number%20%7B%0D%0A%20%20%20%20if%20(a%20%3D%3D%3D%20A.Foo)%20return%200%3B%0D%0A%20%20%20%20if%20(a%20%3D%3D%3D%20A.Bar)%20return%201%3B%0D%0A%20%20%20%20return%20assertNever(a)%3B%0D%0A%7D

Related Issues:

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先,在启用 strictNullChecks 的情况下复现 issue 的 TypeScript 代码,并比较 if 和 switch 分支。跟踪 compiler 对错误函数的控制流缩窄和缺少返回分析。当该案例中报告的 diagnostic 得到解决,且回归覆盖确认了该行为时,即视为完成。

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

评估

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

把新 issue 发到你的邮箱

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