DEV Community

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

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 :)