loading...

Implement a type-safe version of Node's Promisify in 7 lines of TypeScript

_gdelgado profile image Gio ・1 min read
type Callback<A> = (args: A) => void;

const promisify = <T, A>(fn: (args: T, cb: Callback<A>) => void): ((args: T) => Promise<A>) =>
  (args: T) => new Promise((resolve) => {
    fn(args, (callbackArgs) => {
      resolve(callbackArgs);
    });
  });

Check out this video that demonstrates type inference in action!

I'm using type-variables T and A to generecally implement this function over the original function's arguments, and the callback function's arguments.

Exercises:

  • Did I need to define an inline anonymous function for the second argument of fn? How else could I have invoked fn?

  • Note that my Callback type isn't a typical error-first callback like in a lot of node APIs (this is just because the functions I'm trying to promisify aren't error-first callbacks). So I'll leave it to you as an exercise to refactor my promisify function to reject when an error on an error-first callback is not null ;)

Posted on by:

_gdelgado profile

Gio

@_gdelgado

Freelance Software Engineer & Consultant GitHub: https://github.com/supermacro/

Discussion

markdown guide