【问题标题】:Extending a class to an interface in TypeScript将类扩展为 TypeScript 中的接口
【发布时间】:2018-09-23 11:05:58
【问题描述】:

http://www.typescriptlang.org/docs/handbook/interfaces.html“接口扩展类” 部分下的信息表明

接口甚至继承基类的私有成员和受保护成员 类。

但是,当我尝试时,TypeScript 提示错误,指出派生类错误地实现了接口 - 并且基类的 privateprotected 成员在派生类。

以下是代码:

class View {
  private content: any;
  protected presentation: string;
  public render() {
    console.log("View::render()");
    console.log("content: ", this.content);
    console.log("presentation: ", this.presentation);
  }
  constructor(c: string, p: string) {
    this.content = c;
    this.presentation = p;
  }
}

interface ViewShadow extends View {}

class MobileDisplay implements ViewShadow {
  private content: any;
  protected presentation: string;

  public render() {
    console.log("View::render()");
    console.log("content: ", this.content);
    console.log("presentation: ", this.presentation);
  }
  constructor(c: string, p: string) {
    this.content = c;
    this.presentation = p;
  }
}

【问题讨论】:

  • 你能分享一下确切的错误信息吗?

标签: typescript typescript2.0


【解决方案1】:

如果你在一个接口中继承一个类,该接口将继承该类的私有成员,但问题是你不能实现私有字段,编译器将不接受任何作为protected/的实现private 原始字段以外的字段。因此,您的实现必须继承 View 才能正确实现 ViewShadow 接口:

class MobileDisplay  extends View implements ViewShadow {
}

通常认为非公共字段不应成为要实现的接口的一部分。如果您只想要公共字段/方法,您可以使用映射类型:

interface ViewShadow extends Pick<View, keyof View> { }

class MobileDisplay implements ViewShadow {
    private content: any;
    protected presentation: string;
    public render() {
        console.log("View::render()");
        console.log("content: ", this.content);
        console.log("presentation: ", this.presentation);
    }
    constructor(c: string, p: string) {
        this.content = c;
        this.presentation = p;
    }
}

【讨论】:

    【解决方案2】:

    您需要继续阅读文档。在你引用的那句话之后的两句话,它说:

    这意味着当您创建一个扩展具有私有或受保护成员的类的接口时,该接口类型只能由该类或其子类实现。

    (强调我的)。

    所以你需要

    class MobileDisplay extends View implements ViewShadow
    

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 2021-08-07
      • 2015-04-01
      • 2016-07-06
      • 2022-12-06
      • 2017-11-29
      • 2016-12-18
      • 2021-03-07
      相关资源
      最近更新 更多