3

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?

Yang Liu
  • 541
  • 9
  • 26
  • There are also answers here although they are quite ancient and don't use good techniques IMO https://stackoverflow.com/q/1714786/10873797 – sno2 Mar 16 '22 at 00:47

3 Answers3

7

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();
}
sno2
  • 3,274
  • 11
  • 37
1

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()
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
0

I am converted type to query string like this:

 var queryString = Object.keys(params).map(key => key + '=' + params[key as keyof IChatAsk]).join('&');

the type defined like this:

export type ChatAsk = {
    prompt: string;
    cid: number;
}
Dolphin
  • 29,069
  • 61
  • 260
  • 539