I’m using Vue with TypeScript and would like to call the app with the url
so I don’t need a route hash. Given the following code:
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);
// ...
};