← 中文资源

简体中文版本

UnionToIntersection 合并选项集合

用函数参数位置的逆变把联合翻转成交集,再 infer 一轮提取出来:合并后的选项集合要求每个成员的键同时出现,一行类型即可完成合并。

阅读英文原文

实现说明

模块级对象字面量,键名固定:retries。

使用要点

  • 每一步打印都带着自己的标签:union accepts partial:。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。

核心语句

type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (
  arg: infer I,
) => void

代码示例

// A union of option objects becomes an intersection: every member's keys
// must be present at once. The contravariant function position flips the
// union, and a second inference round extracts it.
type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (
  arg: infer I,
) => void
  ? I
  : never;

type ServerOptions = { retries: number } | { timeoutMs: number };
type Merged = UnionToIntersection<ServerOptions>;

const merged: Merged = { retries: 3, timeoutMs: 1_500 };
console.log(merged.retries, merged.timeoutMs);

// Without the helper, a plain union accepts any single member alone
const loose: ServerOptions = { retries: 3 };
console.log('union accepts partial:', 'retries' in loose && !('timeoutMs' in loose));