Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Argument of type 'Location' is not assignable to parameter of type 'string | URL'

I’m using Vue with TypeScript and would like to call the app with the url

http://localhost:5173?foo=bar

so I don’t need a route hash. Given the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const getUrlParameter = (name: string) => {
  const url = new URL(window.location);

  const parameter = url.searchParams.get(name);

  // ...
};

It returns bar when passing in 'foo' so it seems it’s working as expected. But TS comes up with the error message

TS2345: 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, toJSON

Should I suppress this message? Are there ways to fix it?

>Solution :

It looks like you’re trying to use the URL constructor to create a new URL object from the current window.location, but TypeScript is giving you an error because it doesn’t know that window.location is a valid argument for the URL constructor. To fix this, you can either suppress the error using the @ts-ignore directive, or you can provide TypeScript with the correct type information by using a type assertion. Here’s an example of how you could do that:

const getUrlParameter = (name: string) => {
  // Use a type assertion to tell TypeScript that the `window.location` object
  // has the properties that the `URL` constructor expects.
  const url = new URL(window.location as any);

  const parameter = url.searchParams.get(name);

  // ...
};

Alternatively, you could use the URL object from the globalThis global object instead of window.location, which may be a cleaner solution:

const getUrlParameter = (name: string) => {
  const url = new URL(globalThis.location.href);

  const parameter = url.searchParams.get(name);

  // ...
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading