【发布时间】: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)
我错过了什么吗? 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