I have a piece of TypeScript code like this
function askLogin(): never {
location.replace('/login');
}
However, typescript report an error:
A function returning 'never' cannot have a reachable end point.
Should I change to void return type here? Or what the best I can do here?
Although changing the
locationhas the effect of navigating, possibly away from the current page, it doesn't necessarily immediately stop execution of JavaScript. You can test for yourself that, in at least some browsers, some amount of JavaScript will still be run afterward. See Does changing window.location stop execution of javascript?.So the TS library call signature for
location.replacereturnsvoidand notnever. And similarly, youraskLogin()function should returnvoidand notnever, since it is quite likely that your function will return normally. For example, in my browser (Firefox) I see"HELLO"in the console logs for the following code:Playground link
If you want
askLogin()to returnnever, you'll need to make sure the function does not return normally yourself, say bythrowing an exception:Playground link
That doesn't necessarily stop all execution everywhere, since some outer scope might
catchyour exception and do stuff. But there's no good way to avoid that, really. (You could try to make your function loop forever instead of throwing, but that has a good chance of preventing the location replace from occurring at all, depending on the browser.)