Yang Liu
Yang Liu

Reputation: 741

How to convert a type to query string?

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?

Upvotes: 4

Views: 5046

Answers (3)

sno2
sno2

Reputation: 4213

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

Upvotes: 8

Dolphin
Dolphin

Reputation: 38835

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

Upvotes: 0

Nick Vu
Nick Vu

Reputation: 15520

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

Upvotes: 2

Related Questions