I'm trying to reload my page after a function has completed, using the method:
window.location = "/"
but I keep getting the typescript error saying I can't assign a string to type location, which is weird because isn't a location always a string?
This is what I tried:
window.location.assign("/");
and it worked, but I don't understand why does the previous solution not work?
window.location is an Object which has the propertly href which is a String. You want window.location.href = "/".
According to the spec, you are allowed to assign a value to window.location:
Though
Window.locationis a read-onlyLocationobject, you can also assign a string to it. This means that you can work withlocationas if it were a string in most cases:location = 'http://www.example.com'is a synonym oflocation.href = 'http://www.example.com'
The issue, as pointed out in this github issue in the TS repo is that window is typed Window & typeof globalThis. And (typeof globalThis)['location'] is typed Location, not Location | string. So it's only complaining about the assignment for half of the applicable types. You can simply cast to Window to allow for assignment like this:
(window as Window).location = "https://stackoverflow.com/";
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