Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created August 15, 2019 14:50
Show Gist options
  • Select an option

  • Save jtmthf/4353bfa1384db23d2d339a38ea8be97a to your computer and use it in GitHub Desktop.

Select an option

Save jtmthf/4353bfa1384db23d2d339a38ea8be97a to your computer and use it in GitHub Desktop.
const handler: ProxyHandler<URLSearchParams> = {
get(target, prop: string) {
const values = target.getAll(prop);
return values.length === 1 ? values[0] : values;
},
set(target, prop: string, value) {
target.delete(prop);
Array.isArray(value) ? value.forEach(v => target.append(prop, v)) : target.set(prop, value.toString())
return true;
},
has(target, prop: string) {
return target.has(prop)
},
deleteProperty(target, prop: string) {
target.delete(prop);
return true;
},
ownKeys(target) {
return [...target.keys()]
}
}
const params = new URLSearchParams('foo=1&bar=2');
const paramsProxy = new Proxy(params, handler) as any as { [key: string]: string | string[]; };
console.log(paramsProxy.foo) // '1'
console.log(paramsProxy.bar) // '2'
paramsProxy.foo = ['1', '3']
console.log(paramsProxy.foo) // ['1', '3']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment