返回“从不”的函数无法到达终点

时间:2018-12-21 12:57:04

标签: typescript

在语句A function returning 'never' cannot have a reachable end)上出现: never的奇怪错误

interface Result {
    data: string;
}
function logResult(config: Result): never {
    console.log(config.data)
}

logResult({ data: 'This is a test' });

我已经创建了一个typescript playground example with code above

我在做什么错,为什么会出现此错误?

2 个答案:

答案 0 :(得分:3)

never表示将永远不会到达函数的结尾。 This blog gives a good overview of its use

在您的情况下,您的函数的结尾已达到,只是没有返回值。

您想要一个void返回类型来指示缺少返回值:

function logResult(config: Result): void {

答案 1 :(得分:2)

发生此错误是因为您要结束一个应“返回”从不输入类型的函数。

在2种情况下,函数应该不返回 类型:

  1. 在无休止的循环中,例如while(true){}类型的循环
  2. 抛出错误的函数,例如function foo(){throw new Exception('Error message')}

所以问题是您正在到达一个不应该达到终点的函数中达到终点。