【问题标题】:Why does abstract class have to implement all methods from interface?为什么抽象类必须实现接口中的所有方法?
【发布时间】:2017-06-16 16:29:03
【问题描述】:
   interface BaseInter{
      name : string;
      test();
    }

    abstract  class Abs implements  baseInter{
    }

在 TypeScript 中,编译器抱怨该类错误地实现了接口:

abs 类型中缺少名称。

这里Abs是一个抽象类,那我们为什么要在那边实现接口呢?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您需要重新编写接口中的所有成员/方法,并将abstract 关键字添加到它们,所以在您的情况下:

    interface baseInter {
        name: string;
        test();
    }
    
    abstract class abs implements baseInter {
        abstract name: string;
        abstract test();
    }
    

    (code in playground)

    有一个建议:Missing property declaration in abstract class implementing interfaces,但因为这个原因被拒绝了:

    虽然,不写声明的方便是 很好,这种变化可能引起的混乱/复杂性会 不保证。通过检查声明,尚不清楚哪个 成员出现在类型上,是所有属性、方法还是 带有调用签名的属性;它们会被认为是抽象的吗? 可选?

    【讨论】:

      【解决方案2】:

      你可以通过一个克服编译时错误的小技巧得到你想要的:

      interface baseInter {
          name : string;
          test();
      }
      
      interface abs extends baseInter {}
      
      abstract class abs implements baseInter{
      }
      

      这个技巧利用了 Typescript 的 Declaration Merging,最初是在 here 上提出的,并发布在一个相关的 SO 问题 here 上。

      【讨论】:

        【解决方案3】:

        接口用于定义关于对象形状的契约。

        使用构造函数将属性传递给类

        interface BaseInter{
          name : string;
          test(): boolean;
        }
        
        abstract class Abs implements BaseInter{
          constructor(public name: string){}
          test(): boolean{
            throw new Error('Not implemented')
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-06
          • 2015-02-28
          • 2016-03-08
          • 2016-06-07
          • 1970-01-01
          • 1970-01-01
          • 2015-06-29
          相关资源
          最近更新 更多