When you adjust the location
, it may lead to navigation and potentially moving away from the current page. However, this action doesn't immediately halt the execution of JavaScript. Testing in various browsers reveals that some JavaScript code will continue to run even after the location is changed. You can explore more on this topic by visiting Does changing window.location stop execution of javascript?.
For instance, examining the TS library call signature for location.replace
, it indicates a return type of void
rather than never
. Similarly, your askLogin()
function should also return void
instead of never
, as there's a high likelihood that the function will execute normally. This is demonstrated in the console logs of the following code snippet:
function askLogin(): void {
location.replace('/login');
}
askLogin();
console.log("HELLO");
Here's the Playground link for further reference.
If you intend for askLogin()
to return never
, you must ensure that the function doesn't terminate normally by, for example, using throw
to raise an exception:
function askLogin(): never {
location.replace('login');
throw new Error("Replaced URL, Goodbye cruel world");
}
askLogin();
console.log("HELLO"); // error, unreachable code
Check out the Playground link to understand this concept better.
Note that halting all executions may not be possible, as an outer scope could potentially catch
any exceptions thrown and proceed with actions. It's challenging to entirely prevent this, but one workaround could involve creating a function that loops indefinitely instead of throwing an exception. However, this approach may interfere with the location replacement process depending on the browser used.