Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location = "/"; Type 'string' is not assignable to type 'Location | (string & Location)

Tags:

typescript

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?

like image 253
Muathcs Avatar asked Feb 19 '26 19:02

Muathcs


2 Answers

window.location is an Object which has the propertly href which is a String. You want window.location.href = "/".

like image 57
hldev Avatar answered Feb 21 '26 15:02

hldev


According to the spec, you are allowed to assign a value to window.location:

Though Window.location is a read-only Location object, you can also assign a string to it. This means that you can work with location as if it were a string in most cases: location = 'http://www.example.com' is a synonym of location.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/";
like image 27
KyleMit Avatar answered Feb 21 '26 13:02

KyleMit