簡體   English   中英

為什么一種循環風格會給我一個錯誤,而另一種卻沒有?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM