← 中文资源

简体中文版本

可辨识联合与穷尽分支

用共享字面量标签的对象联合表达变体,并以 never 检查的默认分支保证所有情况都被处理。

阅读英文原文

实现说明

底层就是函数 area。 守卫条件成立时抛出 Error,而不是返回一个假值。

使用要点

  • 把 area 当作 API:导入它,其余代码可以忽略。

常见问题

坏输入有失败路径吗?

守卫处(入口)会抛出 Error,非法状态到不了主逻辑。

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 area。

入口签名:export function area(shape: Shape)

核心语句

throw new Error("unhandled shape: " + JSON.stringify(unreachable));
return (shape.base * shape.height) / 2;
return Math.PI * shape.radius ** 2;

代码示例

export type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number }
  | { kind: "triangle"; base: number; height: number };

export function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rect":
      return shape.width * shape.height;
    case "triangle":
      return (shape.base * shape.height) / 2;
    default: {
      const unreachable: never = shape;
      throw new Error("unhandled shape: " + JSON.stringify(unreachable));
    }
  }
}