I'm using Typescript.
I have a type defined like this:
export type SearchStoresParameters = {
storeCategory : string;
latitude: number;
longitude: number;
}
And I'm trying to convert above type object to a query string.
export const searchStores = async (searchStoresParameters : SearchStoresParameters ) => {
var queryString = Object.keys(searchStoresParameters).map((key) => {
return encodeURIComponent(key) '=' encodeURIComponent(searchStoresParameters[key])
}).join('&');
const searchStoresApi = process.env.REACT_APP_BACKEND_SERVICE_API "/stores?" queryString;
const res = await fetch(
searchStoresApi,
);
const response = await res.json();
}
However, above code shows error :
(parameter) searchStoresParameters: SearchStoresParameters
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SearchStoresParameters'.
No index signature with a parameter of type 'string' was found on type 'SearchStoresParameters'.ts(7053)
What's the best way to convert a typescript type to query string?
CodePudding user response:
I would advise using the built-in URLSearchParams
API as it was built to performantly serialize/deserialize search param data. Here is an example program of how you would use it:
const data = { firstName: "Jon", lastName: "Doe" };
console.log(new URLSearchParams(data).toString()); // "firstName=Jon&lastName=Doe"
It also encodes the text as required for URLs:
console.log(new URLSearchParams({ foo: "Can it handle weird text?" }).toString()); // "foo=Can it handle weird text?"
Also, if you are worried about support, consult caniuse and use a polyfill if you want to still use it. Anyways, here is your code adapted to use this Web API:
export const searchStores = async (searchStoresParameters : SearchStoresParameters ) => {
var queryString = new URLSearchParams(searchStoresParameters).toString();
const searchStoresApi = process.env.REACT_APP_BACKEND_SERVICE_API "/stores?" queryString;
const res = await fetch(
searchStoresApi,
);
const response = await res.json();
}
CodePudding user response:
searchStoresParameters[key]
is with a dynamic key, so you need to define your type with a dynamic key too.
export type SearchStoresParameters = {
storeCategory : string;
latitude: number;
longitude: number;
[key: string]: number | string;
}
I think you are trying to parse an object to query strings, so you also can use URLSearchParams which is much simpler
const queryString = new URLSearchParams(searchStoresParameters).toString()