It's been a while since I've used Typescript and I'm having trouble remembering how to properly type guard multiple classes within a switch statement.
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 */
}
}
I have tried various options, such as:
- Using
foo.constructor
- Using
instanceof
inside the case statements - adding an extra member to the three classes to be used in the switch statement
but none of them seem to work (
Function lacks ending return statement and return type does not include 'undefined'
).
Am I mistaken in thinking that this cannot be done with classes?