Distributive Omit Preserves Union Variants

Distribute Omit across each union member so per-variant fields survive, and compare it with the common-keys collapse of plain Omit.

TypescriptData Integrity

Code

typescriptsnippet
30 lines
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(','));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Under the hood

The type-level work is DistributiveOmit<T, K> = T extends unknown ? Omit<T, K> : never, and area shows why it matters: its switch (shape.kind) still reaches radius, width and height because each variant kept its own keys.

Applying it

function area(shape: CleanShape) narrows on shape.kind into the circle and rect branches, computing Math.PI * shape.radius ** 2 or width * height.

The contrast shows up in the output: circle area: 12.57 and rect area: 12 prove the variants survived, while wide keys: kind shows plain Omit<Shape, 'label'> collapsing to the one key every member shares.

Statements that matter

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

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `area` at load time.