[SOLVED] How to convert a type to query string?

Issue

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?

Solution

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%3F"

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();
}

Answered By – sno2

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *