0

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 )
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 2
    Using `typeof` at runtime will not display the compile time type. It correctly outputs `object` which is the JavaScript type for all objects. (There is no way to output the compile time type of `p` or `a` at runtime) - actually since they are classes, you can do `p.constructor.name`. But this will only work for classes. – Tobias S. Dec 08 '22 at 12:08
  • @TobiasS. that is unfortunate ! any idea how to debug it? dynamic casting? I mean something like logging properties of the static type – OrenIshShalom Dec 08 '22 at 12:16
  • JavaScript does not have casting outside of primitives. But what is the problem you are trying to solve? Just displaying the type? – Tobias S. Dec 08 '22 at 12:17
  • I have a complex visiting layout - I'm trying to log the exact visit details for further process – OrenIshShalom Dec 08 '22 at 12:18
  • 1
    [Runtime typesafety in typescript](https://stackoverflow.com/q/59135732) | [What is type erasure?](https://github.com/Microsoft/TypeScript/wiki/FAQ#what-is-type-erasure) – VLAZ Dec 08 '22 at 12:20
  • In the example code of your question, you have one function for each `class` anyway. You can log whatever you want depending on the specific class. – Tobias S. Dec 08 '22 at 12:21
  • @TobiasS. the example is just a demonstration - my real life case involves a situation where knowing the type would help *a lot* – OrenIshShalom Dec 08 '22 at 12:22
  • I guess you should also include an example in the question where knowing the type would be helpful. – Tobias S. Dec 08 '22 at 12:23

0 Answers0