You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue+TypeScript中传入Location构造URL触发TS类型报错的解决方法

问题修复方案

首先不要抑制这个报错,TypeScript的类型检查是为了规避潜在运行时问题,强行抑制只会掩盖类型不匹配的风险。

报错原因

window.location属于Location类型对象,而URL构造函数仅接受string或URL类型参数。虽然浏览器环境里Location和URL有不少相似属性,但TypeScript的类型定义严格区分了这两个类型,因此会抛出类型不兼容的错误。

两种修复方法

方法1:传入window.location.href字符串给URL构造函数

直接用location.href(完整的URL字符串)创建URL对象,完全符合类型要求:

const getUrlParameter = (name: string) => {
  const url = new URL(window.location.href);
  const parameter = url.searchParams.get(name);
  // ...
};

方法2:直接使用window.location.searchParams

浏览器原生的Location对象已经内置了searchParams属性,完全可以跳过创建URL对象的步骤,直接获取参数:

const getUrlParameter = (name: string) => {
  const parameter = window.location.searchParams.get(name);
  // ...
};

这个方法更简洁高效,无需额外创建URL实例。

内容的提问来源于stack exchange,提问作者baitendbidz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:55:17