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?
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.
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.
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.
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:
while(true){}
type loopfunction foo(){throw new Exception('Error message')}
So the problem is you are reaching an end in a function that shouldn't reach an end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With