向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