URL-class not accepting window.location as base-URL

Viewed 565

How come typescript is complaining at window.location:

const url = new URL("/somepath", window.location);

Argument of type 'Location' is not assignable to parameter of type 'string | URL'. Type 'Location' is missing the following properties from type 'URL': password, searchParams, username, toJSONts(2345

but it's perfectly valid JS?

const url = new URL("/somepath", window.location)
console.log(url);

I get that window.location is missing password, searchParams, username, toJSON but it seems like those are irrelevant in order to utilize URL?

Question:

Is this an issue with Typescript or is it a coincidence that URL accepts window.location-object

1 Answers

This is a TypeScript thing. In JavaScript, window.location is an object. However when calling it directly, it provides the href property - the easiest way to think of this is that the .toString() method returns the href property. You should just call the href property directly:

const url = new URL("/somepath", window.location.href);

You could use the location directly by forcing it to be any, or through an unknown then string type, but this just starts to move away from what TypeScript is meant to provide:

// An any type
const url = new URL("/somepath", window.location as any);

// An unknown then string type
const url = new URL("/somepath", window.location as unknown as string);
Related