Created
April 8, 2025 18:45
-
-
Save acquitelol/db8892891ae62393642608876f2cc455 to your computer and use it in GitHub Desktop.
A reimplementation of the `with` feature which was recently removed from TypeScript.
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
| function rosieWith<T>(arg: T, callback: Function) { | |
| const descriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(arg)); | |
| for (const [key, descriptor] of Object.entries(descriptors)) { | |
| typeof descriptor.value === "function" && ((globalThis as any)[key] = descriptor.value.bind(arg)); | |
| } | |
| callback(); | |
| for (const [key, descriptor] of Object.entries(descriptors)) { | |
| typeof descriptor.value === "function" && delete (globalThis as any)[key]; | |
| } | |
| } | |
| rosieWith([1, 2, 3], () => { | |
| console.log(map(x => x * 2)); // [2, 4, 6] | |
| }); | |
| // 実行されたJavaScriptにエラーが発生しました: | |
| // map is not defined | |
| console.log(map(x => x * 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment