5

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

Salmin Skenderovic
  • 1,750
  • 9
  • 22
  • 2
    `window.location` is an object with some magic. The actual URL can be found at `window.location.href`. I guess Typescript is just being strict. (BTW, it won't hurt if you edit the question and add the exact complaint message). – Álvaro González Jun 08 '21 at 14:31
  • I don't know if this is an issue with TS or a coincidence that URL accepts window.location-object? – Salmin Skenderovic Jun 08 '21 at 14:47
  • 1
    Does this answer your question? [Get the current URL with JavaScript?](https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript) – Peter Krebs Jun 08 '21 at 14:55
  • @PeterKrebs no. I've updated the question to clarify – Salmin Skenderovic Jun 09 '21 at 20:12

1 Answers1

6

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);
Dean James
  • 2,491
  • 4
  • 21
  • 29
  • 1
    Would you say that the correct implementation for `new URL` with a base-path would be to provide location.href or location.origin? – Salmin Skenderovic Jun 08 '21 at 18:10
  • 1
    Both will produce the same result, though I would say it makes more sense to use `origin`. The `href` property has been around a lot longer and has lot better browser compatibility, but if you're using the `URL` API, it's a moot point, as that has even less support. – Dean James Jun 08 '21 at 21:31
  • @SalminSkenderovic I was trying to do this in a react app with react-router, and basically react-router modifies the basepath and using href was giving urls with some path duplications in them, with origin it worked as intended. So if you are doing this in an react app, use origin. – Hayk Safaryan Aug 15 '22 at 11:02