Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created December 29, 2023 13:36
Show Gist options
  • Save karol-majewski/6f3f7d944de9c332b221093c0763bb37 to your computer and use it in GitHub Desktop.
Save karol-majewski/6f3f7d944de9c332b221093c0763bb37 to your computer and use it in GitHub Desktop.
Convert synchronous methods to async methods
type PromisifyMethods<T> = {
[K in keyof T]: T[K] extends AnyFunction ? (...parameters: Parameters<T[K]>) => Promise<ReturnType<T[K]>> : T[K];
};
type AsynchronousStorage = PromisifyMethods<Storage>;
export function promisify(storage: Storage): AsynchronousStorage {
return new Proxy(storage, {
get(target, name: string) {
if (typeof target[name] === 'function') {
return async function (...args: unknown[]) {
return Reflect.apply(target[name], storage, args);
};
}
return Reflect.get(target, name, target);
},
}) as unknown as AsynchronousStorage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment