使用 TypeScript 设置 window.location
Posted
技术标签:
【中文标题】使用 TypeScript 设置 window.location【英文标题】:Set window.location with TypeScript 【发布时间】:2012-10-17 21:37:33 【问题描述】:我收到以下 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');
【讨论】:
我注意到,在当今的浏览器中,设置window.location = "some string"
具有特殊行为,请参见此处:***.com/questions/2383401/… - 请参阅有关同站点、同源和 XHR 行为的 cmets。【参考方案2】:
你错过了href
:
标准,将window.location.href
用作window.location
在技术上是一个包含以下内容的对象:
Properties
hash
host
hostname
href <--- you need this
pathname (relative to the host)
port
protocol
search
试试
window.location.href = $link.attr('data-href');
【讨论】:
【参考方案3】:只需添加href
像这样:
window.location.href = $link.attr('data-href');
【讨论】:
这与the accepted answer 中的解决方案相同。 在回答已有答案的旧问题时,请确保提供新颖的解决方案或比现有答案更好的解释。以上是关于使用 TypeScript 设置 window.location的主要内容,如果未能解决你的问题,请参考以下文章
使用 .ts 文件 (TypeScript) 配置 Jest 全局测试设置
Storybook 和 AntDesign 组件 - 如何使用 CRA 和 Typescript 进行设置?
如何使用 Typescript 为 React 设置 Material-UI?
使用 Typescript 的 Webpack:两个配置中的通用设置,那么哪个优先?