Skip to content

Instantly share code, notes, and snippets.

@kamataryo
Created November 4, 2019 23:05
Show Gist options
  • Save kamataryo/84ff9181f3bd19f18ebd14cce0474bb0 to your computer and use it in GitHub Desktop.
Save kamataryo/84ff9181f3bd19f18ebd14cce0474bb0 to your computer and use it in GitHub Desktop.
promisify typing sandbox
type Length<A extends any[]> = A extends { length: infer L } ? L : never;
type Prev<N extends number> = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10][N];
type Last<A extends any[]> = A[Prev<Length<A>>];
type LastParam<F extends (...args: any[]) => any> = Last<Parameters<F>>;
type Callback<T> = (error: Error | null, data?: T | null) => void;
type CallbackData<F> = F extends Callback<infer T> ? T : never;
type BH = (...args: any[]) => any;
const promisify = <H extends BH>(handler: H) => {
return (...args: any[]) => {
return new Promise<CallbackData<LastParam<H>>>((resolve, reject) => {
handler(...args, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
};
const testFunc = (
p1: string,
p2: number,
p3: boolean,
callback: (err: Error | null, data: string | null) => void
) => {
if (p3) {
callback(null, p1 + p2);
} else {
callback(new Error("Invalid Parameter"), null);
}
};
testFunc("a", 1, true, (err, data) => console.log(data));
promisify(testFunc)("a", 1, true)
.then(data => {})
.catch(error => {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment