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 )
8
  • 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. Commented Dec 8, 2022 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 Commented Dec 8, 2022 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? Commented Dec 8, 2022 at 12:17
  • I have a complex visiting layout - I'm trying to log the exact visit details for further process Commented Dec 8, 2022 at 12:18
  • 1
    Runtime typesafety in typescript | What is type erasure? Commented Dec 8, 2022 at 12:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.