Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function returning 'never' cannot have a reachable end

Tags:

typescript

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?

like image 682
zmii Avatar asked Dec 21 '18 12:12

zmii


People also ask

What happens if a function never returns?

Such a function is inferred to have a void return type in TypeScript. A function that has a never return type never returns. It doesn't return undefined , either. The function doesn't have a normal completion, which means it throws an error or never finishes running at all.

Does returning end a function?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

What is never in TypeScript?

TypeScript introduced a new type never , which indicates the values that will never occur. The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception.


Video Answer


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 {
like image 122
Carcigenicate Avatar answered Nov 15 '22 10:11

Carcigenicate


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.

like image 25
WilsonPena Avatar answered Nov 15 '22 12:11

WilsonPena