Created
August 15, 2019 14:50
-
-
Save jtmthf/4353bfa1384db23d2d339a38ea8be97a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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