【问题标题】:Return type specification for wrapped method (TypeScript)包装方法的返回类型规范 (TypeScript)
【发布时间】:2017-01-28 06:46:45
【问题描述】:

我正在尝试将 bcrypt 模块用于 Node 和 TypeScript 的 await / async 选项。 compare 代码相当简单:

    let compare = util.asyncWrap( bcrypt.compare );
    let result = await compare( password, stored );
    return result;

当我通过 TypeScript 编译器运行它时,它会说:

错误 TS2322:类型“{}”不可分配给类型“布尔”。

好吧,很公平,它不知道来自compare 的解析值将是一个布尔值。问题是,我该怎么说呢?只需将 :boolean 添加到 result 对象即可移动错误。

这是我的asyncWrap 函数:

export default function asyncWrap( fn ) {
    return function (...args) {
        return new Promise( function ( resolve, reject ) {
            // Assume the callback handler goes at the end of the arguments
            args.push( function( err, val ) {
                // Assume that err is the first argument and value is the second
                if ( err ) {
                    reject( err );
                }
                else {
                    resolve( val );
                }
            } );

            fn.apply( fn, args );
        } );
    }
}

我应该注意,我知道我可以使用来自 npm 的 bcrypt 的 promified 版本,但是,我刚刚开始使用 TypeScript,想了解它是如何工作的。

【问题讨论】:

    标签: node.js asynchronous typescript bcrypt


    【解决方案1】:

    您的代码中没有指定操作的返回值是布尔值,因此编译器无法推断。

    这应该可以解决问题:

    return new Promise<boolean>(function(resolve, reject) {
        ...
    });
    

    【讨论】:

    • 问题在于asyncWrap 函数可用于包装其他可能返回其他类型(如字符串或对象)的函数。如果不重复代码,我不知道如何告诉它对于这种特定情况它应该是一个布尔值。
    【解决方案2】:

    根据 Nitzan 所说,您可以use Generics 执行此操作:

    util.asyncWrap<boolean>( bcrypt.compare );
    

    asyncWrap 变为:

    export default function asyncWrap<T>( fn: Function ): Function {
        return function (...args): Promise<T> {
            return new Promise<T>( function ( resolve: Function, reject: Function ) {
                // Assume the callback handler goes at the end of the arguments
                args.push( function( err: Object, val: any ) {
                    // Assume that err is the first argument and value is the second
                    if ( err ) {
                        reject( err );
                    }
                    else {
                        resolve( val );
                    }
                } );
    
                fn.apply( fn, args );
            } );
        };
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 2022-11-04
      • 1970-01-01
      相关资源
      最近更新 更多