实现说明
分布式 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(','));