【问题标题】:Property 'forEach' does not exist on type 'void'“void”类型上不存在属性“forEach”
【发布时间】:2021-08-05 10:05:07
【问题描述】:

下面的代码是: 1. 读取一个文件夹。 2.合并和自动裁剪图像。 3. 将最终图像保存为 png 文件。

const filenames = fs.readdirSync('./in').map(filename => {
  return path.parse(filename).name
})

const finalImages = filenames.forEach(async filename => {
  const bottomImage = await jimp.read(`./in/${filename}.png`)
  const topImage = await jimp.read('./dots.png')
  const file = bottomImage
    .composite(topImage, 0, 0)
    .autocrop(false)
  return {
    filename,
    file
  }
})

finalImages.forEach((finalImage: any) => {
  finalImage.file.write(`./out/${finalImage.filename}.png`)
})

我收到此打字稿错误:

类型“void”上不存在属性“forEach”。

可能是什么原因,如何解决?

【问题讨论】:

标签: javascript node.js typescript types


【解决方案1】:

我怀疑你想使用的是 map 而不是 forEachmap 迭代一个数组并返回一个新数组,而 forEach 只是简单地迭代而不返回任何内容。

这就是为什么 TS 编译器推断 finalImages 的类型是 void

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 2019-12-01
    • 2019-03-18
    • 2018-08-11
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多