132

I am getting an error with the following TypeScript code:

 ///<reference path='../../../Shared/typescript/jquery.d.ts' />
 ///<reference path='../../../Shared/typescript/jqueryStatic.d.ts' />

 function accessControls(action: Action) {
    $('#logoutLink')
        .click(function () {
            var $link = $(this);
            window.location = $link.attr('data-href');
        });

 }

I am getting an underlined red error for the following:

$link.attr('data-href'); 

The message says:

Cannot convert 'string' to 'Location': Type 'String' is missing property 'reload' from type 'Location'

Does anyone know what this means?

5 Answers 5

254

window.location is of type Location while .attr('data-href') returns a string, so you have to assign it to window.location.href which is of string type too. For that replace your following line:

window.location = $link.attr('data-href');

for this one:

window.location.href = $link.attr('data-href');
2
  • 5
    I note that in browsers today, setting window.location = "some string" has special behaviour, see here: stackoverflow.com/questions/2383401/… - see the comments regarding same-site, same-origin and XHR behaviour.
    – Dai
    Commented Dec 16, 2019 at 5:54
  • While implementing a complex PayPal integration, I noticed a very compelling reason to use window.location, instead of window.location.href: it does not require SAME ORIGIN.
    – Top-Master
    Commented Apr 11, 2022 at 14:54
44

you have missed the href:

Standard, To use window.location.href as window.location is technically an object containing:

Properties
hash 
host 
hostname
href    <--- you need this
pathname (relative to the host)
port 
protocol 
search 

try

 window.location.href = $link.attr('data-href');
0
8

There's an assign method on the Location interface that plays perfectly well with typescript when passed a string and works the same as window.location = LOCATION.

window.location.assign('http://example.com');
interface Location {
    ...
    /** Navigates to the given URL. */
    assign(url: string | URL): void;
}

The method seems to have be around for a long time (IE 5.5!).

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

3

While implementing a complex PayPal integration, I noticed a very compelling reason to use window.location, that it does not require SAME ORIGIN.

Hence we did something like:

(<any> window).location = myUrl;

Instead of:

window.location.href = myUrl;

Where in OP's case:

var myUrl = $link.attr('data-href');
-3

Just add href

Like this:

window.location.href = $link.attr('data-href');
1
  • 2
    This is the same solution as in the accepted answer. When answering older questions that already have answers, please make sure you provide either a novel solution or a significantly better explanation than existing answers.
    – Eric Aya
    Commented Sep 20, 2021 at 8:00