I seem to be losing type info using the visitor design pattern in typescript:
abstract class AbsVisitor
{
public abstract visitPerson(p: Person): void;
public abstract visitAddress(p: Address): void;
}
class StrVisitor extends AbsVisitor
{
public visitPerson(p: Person): void {
console.log(`XXX ${typeof p} XXX`) // <--- type Person is lost !
console.log(`name: ${p.name}`);
}
public visitAddress(a: Address): void {
console.log(`XXX ${typeof a} XXX`) // <--- type Address is lost !
console.log(`{a.street}( ${a.num} )`);
}
}
class Person {
constructor(public name: string){}
public accept(v: AbsVisitor){ v.visitPerson(this); }
}
class Address {
constructor(public street: string, public num: number){}
public accept(v: AbsVisitor){ v.visitAddress(this); }
}
let v = new StrVisitor();
let p = new Person("moish");
let a = new Address("5th Ave.", 62);
p.accept(v);
a.accept(v);
When I run it, I get the sub-optimal (incorrect?) result:
XXX object XXX
name: moish
XXX object XXX
{a.street}( 62 )
typeofat runtime will not display the compile time type. It correctly outputsobjectwhich is the JavaScript type for all objects. (There is no way to output the compile time type ofporaat runtime) - actually since they are classes, you can dop.constructor.name. But this will only work for classes.