← 中文资源

简体中文版本

分布式 Omit 保留联合变体

让 Omit 分发到每个联合成员,保留各自字段,并与普通 Omit 只留公共键的行为对照。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

circle rect
circle area: 12.57
rect area: 12
wide keys: kind

实现说明

分布式 Omit 保留联合变体可以归结为函数 area。

使用要点

  • 跑完文件,输出里会留下标记——circle area:、rect area:、wide keys:。

常见问题

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

除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 area。

签名一览:function area(shape: CleanShape)

核心语句

return Math.PI * shape.radius ** 2;
return shape.width * shape.height;

代码示例

type Shape =
  | { kind: 'circle'; radius: number; label: string }
  | { kind: 'rect'; width: number; height: number; label: string };

// 普通 Omit 只保留联合成员的公共键,变体字段会消失
type WideOmit = Omit<Shape, 'label'>;

// Distributive Omit: distribute over every union member, keeping each variant's keys
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;

type CleanShape = DistributiveOmit<Shape, 'label'>;

const circle: CleanShape = { kind: 'circle', radius: 2 };
const rect: CleanShape = { kind: 'rect', width: 3, height: 4 };
console.log(circle.kind, rect.kind);

function area(shape: CleanShape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'rect':
      return shape.width * shape.height;
  }
}

console.log('circle area:', area(circle).toFixed(2));
console.log('rect area:', area(rect));

const wide: WideOmit = { kind: 'circle' };
console.log('wide keys:', Object.keys(wide).join(','));