如何分解TypeScript“ Discriminated Union”开关块并同时使其详尽无遗

Whi*_*ght 4 functional-programming discriminated-union typescript

对于我的应用程序,我使用了TypeScript 手册中所述的带有完全检查性的“ 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); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

我刚刚发现(通过实验,不是因为在任何地方的文档中都提到了这一点),您确实可以使用多个判别建立一个区分联合的类型层次结构

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;
    }
}
Run Code Online (Sandbox Code Playgroud)