使用 TypeScript 设置 window.location

2022-08-30 05:13:15

我收到以下 TypeScript 代码的错误:

 ///<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');
        });

 }

我收到以下带下划线的红色错误:

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

该消息说:

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

有谁知道这意味着什么?


答案 1

window.location在返回字符串时是类型的,因此您必须将其分配给字符串类型。为此,请替换以下行:Location.attr('data-href')window.location.href

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

对于这个:

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

答案 2

您错过了 :href

标准,按原样使用,从技术上讲是包含以下内容的对象:window.location.hrefwindow.location

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

尝试

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