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

时间:2021-05-15 14:24:23

标签: javascript node.js typescript types

下面的代码是: 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`)
})

我收到此打字稿错误:

enter image description here

<块引用>

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

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

1 个答案:

答案 0 :(得分:1)

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

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