DEV Community

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

Collapse
 
sfsr12 profile image
sfsr12

This is awesome, and I've been using it and just spent the better part of the day trying to wrap my head around how you would write a promisifyAll version of this that would promisify all of the properties of an object. Assuming they were all "promisifiable".

If you could give me any hint that points in the right direction I would be much obligied.

Thanks!

Collapse
 
_gdelgado profile image
Gio

This is quite tricky!

You will need to infer the type of function arguments.

See here:

stackoverflow.com/questions/518516...

You can then access each individual argument's type by accessing the index of the type:

const fn1 = (args: string, cb: Callback<string>): void => {
    setTimeout(() => {
     cb(null, 'example1')
    }, 1000)
}

// P is of type 'string' since 'string' is the 0'th argument
type P = Parameters<typeof fn1>[0]
Enter fullscreen mode Exit fullscreen mode

You'll also need a Mapped Type (docs on mapped types):

type CallbackObj = Record<string, (args: any, cb: Callback<any>) => void>

type PromisifiedObject<T extends CallbackObj> = {
  [P in keyof T]: (args: Parameters<T[P]>[0]) => Promise<????>; 
};
Enter fullscreen mode Exit fullscreen mode

Hope that helps. The ???? is there for you to figure out :)