【问题标题】:Why does one loop style give me an error but the other doesn't?为什么一种循环样式会给我一个错误,而另一种却没有?
【发布时间】:2021-10-21 03:49:51
【问题描述】:

前言:我正在使用 typescript 和 node-pg(Postgres for node)来填充一组 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));

【问题讨论】:

  • 为什么不使用WHERE game_id IN ( 1, 2, 3, 4, 5 ) 的单个查询?这样运行起来会快很多。
  • 这是一个很好的观点,我仍在研究我的数据库技能,所以我会改变它。谢谢! @戴
  • 第二个代码示例中queryArray的声明是什么?
  • 同第一个let queryArray = []

标签: typescript loops for-loop node-pg-pool


【解决方案1】:

问题出在这一行:

let queryArray = [];

TypeScript 会将queryArray 的类型推断为any[],因为您尚未使用任何可用于推断整个数组类型的类型化元素对其进行初始化。默认情况下,TypeScript 配置为不允许 implicit any 类型,因此这会导致编译失败。

如果你把那行改成这样,告诉 TypeScript 尽管queryArray 现在是空的,你只打算在里面放数字(例如 - 如果你的意思是它有另一种类型,那么当然使用它而是),那么它应该可以解决这个问题,因为它将不再具有隐含的any 类型:

let queryArray: number[] = [];

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 1970-01-01
    • 2014-04-12
    • 2019-11-02
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    相关资源
    最近更新 更多