从v8.0.0起,Node提供了util.promisify() API。现在,我正在尝试将一些回调样式的方法转换为异步/等待样式。
在 typescript 上,util.promisify()
可能不会继承方法签名:
import fs = require('fs');
export namespace AsyncFs {
export const lstat = util.promisify(fs.lstat);
// there's no method signature, only shows as "Function"
}
尽管我们可以为每种方法添加新的签名...
export const lstat = util.promisify(fs.lstat) as (path: string | Buffer) => fs.Stats;
因此,我正在寻找一种自动继承签名的好方法。可能吗?你有什么好主意吗?
谢谢。
最佳答案
如果内部未由TS处理,那么您可能必须自己做类似于what they do for Bluebird's promisify() static function in DefinitelyTyped的操作来为util.promisify()
定义类型。
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>;