示例工程 08-unions-intersections
08-unions-intersections/02-discriminated-union/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// 演示:可辨识联合用 kind 字段收窄,漏分支由 never 拦截
export type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'rect'; width: number; height: number };
function assertNever(value: never): never {
throw new Error(`unreachable: ${JSON.stringify(value)}`);
}
export function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.side ** 2;
case 'rect':
return shape.width * shape.height;
default:
return assertNever(shape);
}
}
export function run(log: (msg: string) => void = console.log): string[] {
const lines = [
area({ kind: 'circle', radius: 1 }).toFixed(2),
String(area({ kind: 'square', side: 3 })),
String(area({ kind: 'rect', width: 2, height: 5 })),
];
for (const line of lines) {
log(line);
}
return lines;
}