0

I m trying to create a Visitor Design pattern but i'm facing a compilation error that i was unable to solve despites the hours I tried finding a solution ...

Visitor interface :

export interface Visitor {
    visit(a: A): X;
    visit(b: B): Y;
}

Visitor implementation :

export class VisitorImp implements Visitor {

    visit(a: A): X {
      return a.getX();
    }

    visit(b: B): Y{
     return b.getY();
    }
}

With that, I have the following compilation Error :

Property 'visit' in type 'VisitorImp' is not assignable to the same property in base type 'Visitor'.
  Type '(a: A) => X' is not assignable to type '{ (a: A): X; (b: B): Y; }'.
    Type 'X' is missing the following properties from type Y

I really hope someone can help me on that because it is driving me crazy right now !

1 Answer 1

2

I haven't tested this but you could try

export interface Visitor {
    visit: ((a: A) => X) | ((b: B) => Y);
}

Got that from skimming this site.

EDIT:

So it appears that this is not prettily implementable. This should do the trick:

interface Visitor {
    visit(a: String): Number;
    visit(b: Number): String;
}

class VisitorImp implements Visitor {

    visit(a: String): Number;
    visit(b: Number): String;
    visit(a: String | Number): Number | String {
        if(a instanceof String) {
            return 0;
        } else {
            return "";
        }
    }
}

where String/Number are A/B. As seen here.

Sign up to request clarification or add additional context in comments.

2 Comments

When I use this, i have the following error : Duplicate function implementation on each : visit(a: A): X { return a.getX()}
Your comment do the trick, thank you a lot for that. Unfortunatly and as you said, it is not a pretty solution. So what I think I'll do is that i will change the visitor pattern a bit by changing the name of the Visitor function : visitA(a: A): X and visitB(b: B): Y

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.