【问题标题】:Error in functions overload in TypeScript : Visitor PatternTypeScript 中的函数重载错误:访问者模式
【发布时间】:2021-06-20 15:49:48
【问题描述】:

我正在尝试创建访问者设计模式,但我遇到了一个编译错误,尽管我尝试找到解决方案的时间很长,但我无法解决...

访客界面:

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

访客实现:

export class VisitorImp implements Visitor {

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

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

这样,我有以下编译错误:

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

我真的希望有人可以帮助我,因为它现在让我发疯!

【问题讨论】:

    标签: typescript interface overloading visitor-pattern


    【解决方案1】:

    我没有测试过,但你可以试试

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

    从浏览this 网站中得到。

    编辑:

    所以看起来这不是很容易实现。这应该可以解决问题:

    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 "";
            }
        }
    }
    

    其中字符串/数字是 A/B。如here所见。

    【讨论】:

    • 当我使用它时,我有以下错误:Duplicate function implementation 每个:visit(a: A): X { return a.getX()}
    • 您的评论可以解决问题,非常感谢您。不幸的是,正如你所说,这不是一个很好的解决方案。所以我想我会做的是,我将通过更改 Visitor 函数的名称来稍微改变访问者模式:visitA(a: A): XvisitB(b: B): Y
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多