对于我的应用程序,我使用了TypeScript manual中所述的带有完全检查性的“ Discriminated Union”模式。 时间流逝,最终我的交换机最终包含了50多个案例。
所以我的问题是:有什么好的解决方案可以分解此开关,而又不会使其穷举?
换句话说,如何将其拆分,如果可以帮助我将这些并集逻辑上划分为子类型(例如,下面的形状可以划分为等边形和其他形状):
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
//... 50 more shape kinds
type Equilateral = Square | Circle /*| 25 more...*/;
type Other = Rectangle /*| 25 more...*/;
type Shape = Equilateral | Other;
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
/*
...
... a lot of code lines
...
*/
default: return assertNever(s);
}
}
答案 0 :(得分:4)
我刚刚发现(通过实验,不是因为在任何地方的文档中都提到了它),您确实可以使用多个判别式建立受歧视联合的类型层次结构:>
interface Square {
shape_kind: "equilateral";
kind: "square";
size: number;
}
interface Circle {
shape_kind: "equilateral";
kind: "circle";
radius: number;
}
interface Rectangle {
shape_kind: "rectangle";
width: number;
height: number;
}
type Equilateral = Square | Circle
type Shape = Equilateral | Rectangle;
function area(s: Shape) {
switch (s.shape_kind) { // branch on "outer" discriminant
case "equilateral":
// s: Equilateral in here!
return area_root(s) ** 2;
case "rectangle":
return s.height * s.width;
}
}
function area_root(e: Equiliteral) {
switch (s.kind) { // branch on "inner" discriminant
case "square": return s.size;
case "circle": return Math.sqrt(Math.PI) * s.radius;
}
}