Skip to content

Instantly share code, notes, and snippets.

@acquitelol
Created April 8, 2025 18:45
Show Gist options
  • Select an option

  • Save acquitelol/db8892891ae62393642608876f2cc455 to your computer and use it in GitHub Desktop.

Select an option

Save acquitelol/db8892891ae62393642608876f2cc455 to your computer and use it in GitHub Desktop.
A reimplementation of the `with` feature which was recently removed from TypeScript.
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