A function returning 'never' cannot have a reachable end

Viewed 1870

There is strange error appearing A function returning 'never' cannot have a reachable end), on statement : never

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

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

I've created a typescript playground example with code above

What I am doing wrong and why this error appears?

2 Answers

never means that the end of the function will never be reached. This blog gives a good overview of its use.

In your case though, the end of your function is reached, it just doesn't return a value.

You want a void return type to indicate a lack of returned value:

function logResult(config: Result): void {

This error happens because you are ending a function that should "return" a never type.

There are 2 cases where functions should return never type:

  1. In an unending loop e.g a while(true){} type loop
  2. A function that throws an error e.g function foo(){throw new Exception('Error message')}

So the problem is you are reaching an end in a function that shouldn't reach an end.

Related