Search code examples
typescriptinterfaceoverloadingvisitor-pattern

Error in functions overload in TypeScript : Visitor Pattern


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 !


Solution

  • 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.