代码之家  ›  专栏  ›  技术社区  ›  Ettapp

switch语句中的类型保护类

  •  1
  • Ettapp  · 技术社区  · 2 年前

    我已经很多年没有使用Typescript了,不记得也找不到如何正确地在switch语句中键入guard许多类。

    class A {}
    class B {}
    class C {}
    
    type OneOfThem = A | B | C;
    
    function test(foo: OneOfThem): string {
        switch(/* something using foo */) {
            /* A */:
                return "A";
            /* B */:
                return "B";
            /* C */:
                return "C";
    
            /* should not need to use "default" as all cases are handled */
        }
    }
    

    我找到并尝试了几个选项,如:

    但它们都不起作用( Function lacks ending return statement and return type does not include 'undefined' ).

    我的记忆力是不是在耍花招,而这在课堂上是不可能的?

    1 回复  |  直到 2 年前
        1
  •  0
  •   ghybs    2 年前

    向switch语句中要使用的三个类添加一个额外的成员

    对于您的案例来说,这可能是最简单的解决方案:它使用 Discriminated Union ,通过添加 判别式 每个类的成员,以便您(和TypeScript)能够区分 foo 来自哪个类:

    class A {
        readonly kind = "a"
        //       ^? "a" string literal, not just string
    }
    class B {
        readonly kind = "b"
    }
    class C {
        readonly kind = "c"
    }
    

    然后在此基础上简单区分 kind 判别性质:

    function test(foo: OneOfThem): string { // Okay
        switch (foo.kind) {
            case "a":
                foo
                //^? A inferred by TS, based on `foo.kind === "a"` type guard
                return "A";
            case "b":
                foo
                //^? B
                return "B";
            case "c":
                foo
                //^? C
                return "C";
            /* should not need to use "default" as all cases are handled */
        }
    }
    

    Playground Link

    推荐文章