[英]Is there any way to inherit method signature with util.promisify on typescript?
From v8.0.0 Node provides util.promisify() API.从v8.0.0 Node 开始提供util.promisify() API。 Now I'm trying to convert some callback-style method into async/await style.
现在我正在尝试将一些回调风格的方法转换成 async/await 风格。 On typescript,
util.promisify()
may not inherit method signature:在打字稿上,
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"
}
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 .如果不是由 TS 内部处理,那么您可能必须自己定义
util.promisify()
的类型,执行类似于他们在绝对类型中为 Bluebird 的 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>;
In cases where the type system fails to infer the promisified function signature, you can provide type hints using generics:在类型系统无法推断出promisified 函数签名的情况下,您可以使用泛型提供类型提示:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.