![](/img/trans.png)
[英]Why does one of these pipes reference `this` correctly and the other one doesn't?
[英]Why does one loop style give me an error but the other doesn't?
前言:我正在使用 typescript 和 node-pg(用於 node 的 Postgres)來填充一組 promise,然后使用Promise.all()
執行它們。
在迭代數字數組並將查詢推入數組時,如果我使用以下代碼遍歷數字數組,則會出現錯誤:
const gameIds = [1,2,3,4,5];
let queryArray = [];
const sql = 'select bettor, fader from wagers where game_id=$1';
gameIds.forEach((gameId: number)=> {
// populate the query array
queryArray.push(DatabaseOperations.dbConnection.query(sql, [gameId]));
});
let allWagersForGames = await Promise.all(queryArray);
將 promise 數組的結果分配給allWagersForGames
時,此代碼給了我一個錯誤。 錯誤狀態: Variable 'queryArray' implicitly has an 'any[]' type.ts(7005)
。
但是,當我按以下方式迭代數字數組時,沒有出現錯誤,我不知道為什么。 我不明白為什么迭代風格的改變會影響是否出現之前的錯誤:
const gameIds = [1,2,3,4,5];
const sql = 'select bettor, fader from wagers where game_id=$1';
for (const gameId of gameIds) {
// populate the query array
queryArray.push(DatabaseOperations.dbConnection.query(sql, [gameId]));
}
// now retrieve all of the data
let allWagersForGames = (await Promise.all(queryArray));
問題來自這一行:
let queryArray = [];
TypeScript 會將queryArray
的類型推斷為any[]
因為您尚未使用任何可用於推斷整個數組類型的類型化元素對其進行初始化。 默認情況下,TypeScript 被配置為不允許隱式any
類型,因此這會導致編譯失敗。
如果您將該行更改為這樣的內容,以告訴 TypeScript 盡管現在queryArray
為空,但您只想在其中輸入數字(例如 - 如果您queryArray
它具有另一種類型,那么當然可以使用它),然后它應該解決這個問題,因為它將不再具有隱式any
類型:
let queryArray: number[] = [];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.