I am making a method to convert querystring to object. The method works well, but typing is reporting an error.
https://jsfiddle.net/h723zuen/2/
const fromQueryString = <
T extends {
[x: string]: string | number | boolean | string[] | number[] | boolean[];
}
>(
querystring: string,
) => {
const out: {
[x: string]: string | number | boolean | string[] | number[] | boolean[];
} = {};
const arr = querystring.split('&');
arr.forEach((a) => {
const [key, value] = a.split('=');
console.log(key, toValue(value), out, key in out);
if (!!key && !!value) {
if (key in out) {
out[key] = Array.isArray(out[key])
? out[key].push(toValue(value))
: [out[key], toValue(value)];
} else {
out[key] = toValue(value);
}
console.log(out);
}
});
return out as T;
};
function toValue(mix: string) {
const str = decodeURIComponent(mix);
if (str === 'false') return false;
if (str === 'true') return true;
return +str * 0 === 0 ? +str : str;
}
