Should I use `never` type for function which call `location.replace`?

37 Views Asked by At

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?

1

There are 1 best solutions below

1
jcalz On

Although changing the location has 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.replace returns void and not never. And similarly, your askLogin() function should return void and not never, 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:

function askLogin(): void {
  location.replace('/login');
}
askLogin();
console.log("HELLO"); 

Playground link

If you want askLogin() to return never, you'll need to make sure the function does not return normally yourself, say by throwing an exception:

function askLogin(): never {
  location.replace('login');
  throw new Error("Replaced URL, Goodbye cruel world");
}
askLogin();
console.log("HELLO"); // error, unreachable code

Playground link

That doesn't necessarily stop all execution everywhere, since some outer scope might catch your 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.)