在语句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
我在做什么错,为什么会出现此错误?
答案 0 :(得分:3)
never
表示将永远不会到达函数的结尾。 This blog gives a good overview of its use。
在您的情况下,您的函数的结尾已达到,只是没有返回值。
您想要一个void
返回类型来指示缺少返回值:
function logResult(config: Result): void {
答案 1 :(得分:2)
发生此错误是因为您要结束一个应“返回”从不输入类型的函数。
在2种情况下,函数应该不返回 类型:
while(true){}
类型的循环function foo(){throw new Exception('Error message')}
所以问题是您正在到达一个不应该达到终点的函数中达到终点。