如何将类型转换为查询字符串?

Yan*_*Liu 3 typescript

我正在使用打字稿。

我有一个这样定义的类型:

export type SearchStoresParameters = {
    storeCategory : string;
    latitude: number;
    longitude: number;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将上述类型对象转换为查询字符串。

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();
}
Run Code Online (Sandbox Code Playgroud)

但是,上面的代码显示错误:

(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)
Run Code Online (Sandbox Code Playgroud)

将打字稿类型转换为查询字符串的最佳方法是什么?

sno*_*no2 7

我建议使用内置URLSearchParamsAPI,因为它是为了高效地序列化/反序列化搜索参数数据而构建的。以下是如何使用它的示例程序:

const data = { firstName: "Jon", lastName: "Doe" };
console.log(new URLSearchParams(data).toString()); // "firstName=Jon&lastName=Doe"
Run Code Online (Sandbox Code Playgroud)

它还根据 URL 的需要对文本进行编码:

console.log(new URLSearchParams({ foo: "Can it handle weird text?" }).toString()); // "foo=Can+it+handle+weird+text%3F"
Run Code Online (Sandbox Code Playgroud)

另外,如果您担心支持,请咨询caniuse ,如果您想继续使用它,请使用polyfill 。无论如何,这里是适合使用此 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();
}
Run Code Online (Sandbox Code Playgroud)