Tank12
Tank12

Reputation: 393

Why does one loop style give me an error but the other doesn't?

Preface: I am using typescript and node-pg (Postgres for node) to populate an array of promises and then execute them all using Promise.all().

When iterating over an array of numbers and pushing queries into an array, I get an error if I loop over the number array using this code:

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);

this code gives me an error when assigning the results of the promise array to allWagersForGames. The error states: Variable 'queryArray' implicitly has an 'any[]' type.ts(7005).

But, when I iterate over the number array the following way, no errors appear and I can not figure out why. I don't see why a change of iteration style should affect whether or not the previous error appears:

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));

Upvotes: 0

Views: 35

Answers (1)

Brooke Hart
Brooke Hart

Reputation: 4049

The problem comes from this line:

let queryArray = [];

TypeScript will infer the type of queryArray as any[] because you haven't initialised it with any typed elements that could be used to infer the type of the whole array. By default, TypeScript is configured to not allow implicit any types, so this causes your compilation to fail.

If you change that line to something this, to tell TypeScript that although queryArray is empty right now you only intend to put numbers in it (for example - if you mean for it to have another type then of course use that instead), then it should fix the issue as it will no longer have an implicit any type:

let queryArray: number[] = [];

Upvotes: 0

Related Questions