2016-09-20 43 views
0

我正在嘗試使用TypeScript的await/async選項爲節點使用bcrypt模塊。該compare代碼是相當簡單:包裝方法的返回類型規範(TypeScript)

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

當我運行檢查了打字稿編譯器,它說:

錯誤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版本,但是,我剛開始用的打字稿,想了解這是如何工作的。

回答

1

您的代碼中沒有指定操作的返回值是布爾值,因此編譯器無法推斷該值。

這也許應該做的伎倆:

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

問題是'asyncWrap'函數可以用來包裝可能會返回其他函數呃類型如字符串或對象。沒有重複的代碼,我不知道如何去告訴它,對於這個特定的情況它應該是一個布爾值。 –

0

建立在什麼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); 
     }); 
    }; 
}