窗口类型.位置

Man*_*aus 0 typescript

我正在尝试使用 URL 对象读取页面 URL。

let url:URL = new URL(window.location)
Run Code Online (Sandbox Code Playgroud)

这会返回一个错误Argument of type 'Location' is not assignable to parameter of type 'string'.

let url:Location = new URL(window.location)
Run Code Online (Sandbox Code Playgroud)

这反而返回Type 'URL' is missing the following properties from type 'Location': ancestorOrigins, assign, reload, replace

那么 URL 对象的类型是什么?

谢谢

VLA*_*LAZ 6

该错误与 的类型无关let url。问题是,根据 TypeScriptnew URL()需要一个字符串,但你给它一个Location对象。这在纯 JavaScript 中可以工作,因为位置将被转换为字符串。

为了满足编译器的要求,您需要更明确地将字符串传递给构造函数:

let url: URL = new URL(window.location.href);
Run Code Online (Sandbox Code Playgroud)

游乐场链接