我已经很多年没有使用Typescript了,不记得也不知道如何正确地在Switch声明中输入保护许多类.
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 */
}
}
我发现并try 了几个选项,例如:
- Using
foo.constructor
- Using
instanceof
inside the case statements - 将额外成员添加到要在Switch陈述中使用的三个类中
但它们都不起作用(Function lacks ending return statement and return type does not include 'undefined'
).
我的记忆是否起了作用,而这在课堂上是不可能的?