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

TypeScript中为何定义options联合类型需使用两个|符号?

为什么readFile的options参数要用两个|定义联合类型?

问题背景

已知联合类型示例:

err: NodeJS.ErrnoException | null

针对以下readFile的TypeScript定义:

function readFile(
path: PathOrFileDescriptor,
options:
    | ({
        encoding: BufferEncoding;
        flag?: string | undefined;
    } & Abortable)
    | BufferEncoding,
callback: (err: NodeJS.ErrnoException | null, data: string) => void,): void

疑问:为何options参数需要用两个|来定义联合类型?


核心原因

这是为了兼容Node.js readFile API的两种合法且常用的调用方式,用联合类型同时允许两种完全不同的参数形式:

  • 第一种:传入完整配置对象
    第一个分支({ encoding: BufferEncoding; flag?: string | undefined; } & Abortable)是一个交叉组合类型:

    • 基础对象包含必填的encoding(指定文件编码,如'utf8')和可选的flag(文件操作标识,如'r')
    • 交叉& Abortable是为了让配置对象支持signal属性,实现通过AbortController取消读取操作的能力
  • 第二种:直接传入编码字符串
    第二个分支BufferEncoding是Node.js提供的语法糖——允许直接传入编码格式字符串(如'utf8')来简化调用,无需包裹成对象

用两个|把这两种类型组合成联合类型后,以下两种写法都能通过TypeScript的类型校验:

// 写法1:完整配置对象
fs.readFile('./demo.txt', { encoding: 'utf8', flag: 'r', signal: abortController.signal }, (err, data) => {
  // ...
})

// 写法2:简写编码字符串
fs.readFile('./demo.txt', 'utf8', (err, data) => {
  // ...
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:29:57