我正在使用打字稿。
我有一個這樣定義的型別:
export type SearchStoresParameters = {
storeCategory : string;
latitude: number;
longitude: number;
}
我正在嘗試將上述型別物件轉換為查詢字串。
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();
}
但是,上面的代碼顯示錯誤:
(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)
將打字稿型別轉換為查詢字串的最佳方法是什么?
uj5u.com熱心網友回復:
我建議使用內置URLSearchParamsAPI,因為它是為高性能序列化/反序列化搜索引數資料而構建的。這是一個如何使用它的示例程式:
const data = { firstName: "Jon", lastName: "Doe" };
console.log(new URLSearchParams(data).toString()); // "firstName=Jon&lastName=Doe"
它還根據 URL 的要求對文本進行編碼:
console.log(new URLSearchParams({ foo: "Can it handle weird text?" }).toString()); // "foo=Can it handle weird text?"
此外,如果您擔心支持,請咨詢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();
}
uj5u.com熱心網友回復:
searchStoresParameters[key]帶有動態鍵,因此您也需要使用動態鍵定義型別。
export type SearchStoresParameters = {
storeCategory : string;
latitude: number;
longitude: number;
[key: string]: number | string;
}
我認為您正在嘗試決議物件以查詢字串,因此您也可以使用更簡單的URLSearchParams
const queryString = new URLSearchParams(searchStoresParameters).toString()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/444752.html
標籤:打字稿
