You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中使用imap与mailparser库遇ReadableStream类型匹配错误

类型不匹配错误:ReadableStream 无法赋值给 Source 类型的原因

问题场景

相关代码:

imap.connect();

imap.once("ready", () => {
  imap.openBox("INBOX", false, async () => {
    imap.search(
      [
        "UNSEEN",
        ["SINCE", new Date()],
      ],
      (err, results) => {
        const f = imap.fetch(results, { bodies: "" });
        f.on("message", async (msg) => {
          msg.on("body", (stream, info) => {
            simpleParser(stream, (error, parsed) => { // 报错位置
            });
          });
        });
        // ...
      }
    );
  });
});

执行时触发以下 TypeScript 类型错误:

No overload matches this call.
  Overload 1 of 3, '(source: Source, callback: (err: any, mail: ParsedMail) => void): void', gave the following error.
    Argument of type 'ReadableStream' is not assignable to parameter of type 'Source'.
      Property 'compose' is missing in type 'ReadableStream' but required in type 'Stream'.
  Overload 2 of 3, '(source: Source, options?: MailParserOptions | undefined): Promise<ParsedMail>', gave the following error.
    Argument of type 'ReadableStream' is not assignable to parameter of type 'Source'.ts(2769)

相同代码在其他项目中可正常运行,该类型错误的产生原因是什么?

错误原因分析

这个类型不匹配问题主要由以下几种情况导致:

  • 依赖版本不一致
    当前项目中 mailparser(simpleParser 所属包)和 imap 库的版本,与正常运行的项目存在差异。新版本的 mailparser 对 Source 类型的定义更严格,要求传入的流必须是 Node.js 原生 Stream(带有 compose 属性),但当前 imap 返回的是浏览器标准的 ReadableStream,二者类型不兼容。

  • 运行环境差异
    两个项目的运行环境不同:一个是纯 Node.js 环境,另一个可能是浏览器环境,或是使用了 browserify、webpack 等打包工具的环境。在非 Node.js 环境下,imap 库可能返回浏览器标准的 ReadableStream,而 mailparser 期望接收 Node.js 原生流,从而触发类型不匹配。

  • 类型定义冲突
    当前项目中可能安装了版本不兼容的类型定义文件(如 @types/node、@types/mailparser、@types/imap),导致 TypeScript 对 Stream 和 ReadableStream 的类型识别出现偏差,进而判定二者不兼容。

内容的提问来源于stack exchange,提问作者TodaysSky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:43:02