user6262880
user6262880

Reputation:

Is there any way to inherit method signature with util.promisify on typescript?

From v8.0.0 Node provides util.promisify() API. Now I'm trying to convert some callback-style method into async/await style. On typescript, util.promisify() may not inherit method signature:

import fs = require('fs');

export namespace AsyncFs {
    export const lstat = util.promisify(fs.lstat);
    // there's no method signature, only shows as "Function"
}

Although we can add new signature for each method...

export const lstat = util.promisify(fs.lstat) as (path: string | Buffer) => fs.Stats;

So I'm looking for a good way to inherit signatures automatically. Is it possible? Do you have any good ideas?

Thanks.

Upvotes: 3

Views: 2047

Answers (2)

jmurzy
jmurzy

Reputation: 3933

In cases where the type system fails to infer the promisified function signature, you can provide type hints using generics:

import { promisify } from 'util';
import jsonwebtoken from 'jsonwebtoken';
import type { VerifyOptions, Secret } from 'jsonwebtoken';


const verify = promisify<string, Secret, VerifyOptions | undefined, JwtExtendedPayload>(jsonwebtoken.verify);

which would yield the result below:

const verify: (arg1: string, arg2: jsonwebtoken.Secret, arg3: jsonwebtoken.VerifyOptions | undefined) => Promise<JwtExtendedPayload>

Upvotes: 1

idbehold
idbehold

Reputation: 17168

If not handled by TS internally, then you will likely have to define the type for util.promisify() yourself doing something similar to what they do for Bluebird's promisify() static function in DefinitelyTyped.

  static promisify<T>(func: (callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): () => Bluebird<T>;
  static promisify<T, A1>(func: (arg1: A1, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1) => Bluebird<T>;
  static promisify<T, A1, A2>(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2) => Bluebird<T>;
  static promisify<T, A1, A2, A3>(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<T>;
  static promisify<T, A1, A2, A3, A4>(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<T>;
  static promisify<T, A1, A2, A3, A4, A5>(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<T>;

Upvotes: 1

Related Questions