【问题标题】:How exactly does work inheritance of a class by an interface?接口对类的工作继承究竟是如何工作的?
【发布时间】:2019-11-08 12:32:37
【问题描述】:

我正在阅读 this section of the TypeScript handbook 并且正在使用修改后的示例:

class Control {
    public state: any;
}

interface SelectableControl extends Control {
    select(): void;
}

class Checkbox implements SelectableControl {
    public state: any;
    select() { }
}

这段代码很好。但是第一季度。我不确定为什么我需要在Checkbox 类中声明属性state,因为它已经存在于SelectableControl 接口中,真的,为什么?

当我更改访问修饰符时会发生更有趣的事情。如果我将state 属性(在ControlCheckbox 中)更改为protected

class Control {
    protected state: any;
}

interface SelectableControl extends Control {
    select(): void;
}

class Checkbox implements SelectableControl {
    protected state: any;
    select() { }
}

然后我得到一个错误“类“复选框”错误地实现接口“SelectableControl”。属性“状态”受保护,但类型“复选框”不是类,继承自“控件”类”(这是翻译到英语)。 第二季度。问题是什么?如果state 已经在这里,在SelectableControl 中,为什么我应该继承Control 类?它与访问修饰符有什么关系?!

现在我将protected 更改为private

class Control {
    private state: any;
}

interface SelectableControl extends Control {
    select(): void;
}

class Checkbox implements SelectableControl {
    private state: any;
    select() { }
}

并且错误已更改!现在是“类“复选框”错误地实现了接口“SelectableControl”。类型有单独的私有属性“状态”声明。” (再次,翻译成英文)。 第三季度。为什么错误发生了变化?!

接口可以继承类的概念对我来说很陌生,所以我无法理解所有这些细微差别......

【问题讨论】:

    标签: typescript inheritance interface


    【解决方案1】:

    TypeScript 是一种结构类型的语言,因此当您从类继承接口时,它相当于只是将类中的字段/方法定义复制粘贴到该接口,即:

    // no extends, just copy-paste
    interface SelectableControl { 
        public state: any;
        select(): void;
    }
    

    您还可以在输出中看到,两个类最终不会相互继承:

    https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=38&pc=1#code/MYGwhgzhAEDCD2A7ALgJ3iaBvAsAKGkOgAcBXAIxAEthoJkxkBTALmjEQE8BufAX3z4qKJqgBmYYE2gBlJiCbAGlJghTpMTAB7NEAExhq0GbPiJ15i5AAoAlGwBu8Knt54BefKEiGAFooBrcngtaCoAW2IFcKYUGDkFJTAVIw1TAiIySho6BmY2Dh4zIghLJTtsaA8+IA

    我相信这应该可以回答您的所有问题,但如果不是,我很乐意扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-19
      • 1970-01-01
      • 2013-10-28
      • 2011-06-26
      • 2021-08-15
      • 2012-06-08
      • 2011-10-11
      • 2013-07-05
      相关资源
      最近更新 更多