简体   繁体   中英

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.

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>;

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM