【问题标题】:Typescript thinks this function would come to an endTypescript 认为这个功能会走到尽头
【发布时间】:2020-01-11 21:30:29
【问题描述】:

想象一下下面的代码:

class MyThrowable {

    // This function will never return, the throw statement is the only one inside of it...
    throw(msg: string):never {
        throw new Error(msg);
    }
}

class SuperThrowable extends MyThrowable {

    // This function does not explicitly throw, but implicitly 
    throw(msg: string):never { 
        super.throw(msg);
    }
}

TypeScript 抛出以下错误,不管代码中提到的事情:

返回“从不”的函数不能有可到达的端点。(2534)

Playground link

我错过了什么吗? TS docs 说:

[...] 绝不是总是抛出异常或从不返回异常的函数表达式或箭头函数表达式的返回类型 [..]

显然是这样,超级方法抛出错误,因此永远不会到达“子类”的末尾,另一个基本相同但有效的示例:

class Throwable {
    sayHello(msg: string): string {
        return "Hello"
    }
}

class SuperThrowable extends Throwable {
    throw(msg: string):string { 
        return super.sayHello(msg);
    }
}

这次它是一个字符串,显然 ts 设法正确解析了类型...

我尝试搜索诸如 TS 无法解析为返回类型、typescript never as return-type not working on calls to superclass 或 typescript superclass从不返回类型但没有成功......

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这似乎是一个 TS 错误。在 TS 3.7 中,我们得到了 "better support for never returning functions",它考虑了在控制流分析中返回 never 的函数。

    在 TS 3.7 之前,您必须 return neverReturningFunction() 才能对代码进行类型检查。 PR #32695 添加了对仅调用函数的支持。

    • 如果您使用return super.throw(msg),则不会出现编译器错误。
    • 如果调用独立函数,则不会出现编译器错误。
    • 如果在this 上调用返回never 的方法,则不会出现编译器错误。

    PR 上有a comment 询问this 和super 的方法,但没有确认是否应该支持。鉴于最后一个项目符号,它似乎应该被支持,这是一个错误,特别是因为这仍然是一个编译器错误!我已经打开了#36147 的报告。

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 2016-08-16
      • 2021-03-18
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多