【问题标题】:Typescript - Why should I rewrite all members to implement an interface?Typescript - 为什么要重写所有成员来实现接口?
【发布时间】:2017-08-06 07:46:07
【问题描述】:

我有一个带有一些可选变量的接口,例如:

interface A {
    id: string;
    name?: string;
    email?: string;
    ...
}

我想做的是

class B implements A {
    constructor(x: string, y: string, ...) {
        this.id = x;
        this.name = y;
        ...
    }

    getName(): string {
        return this.name;
    }
}

我不想重写我将使用的所有成员,我需要一些成员保持可选。每个接口将只用一个类实现,所以如果我重写class B 中的所有成员,那么interface A 将变得毫无用处。

您可能会问“为什么还需要interface A?”。我需要它,因为我在其他项目中使用它,并且我必须使用 extendimplement 它来实现一些功能。

关于该实施的任何解决方案或不同的想法?

【问题讨论】:

  • 您可以使用基类而不是接口 (A) 并使用class B extends A。在这种情况下,您不需要在 B 中声明所有这些成员
  • 我不应该更改interface A,它是由另一个开发人员提供给我的。
  • 在这种情况下你必须实现它..

标签: oop inheritance typescript interface


【解决方案1】:

一种选择是像这样使用Object.assign

interface A {
    id: string;
    name?: string;
    email?: string;
}

class B implements A {
    id: string;
    name: string;
    email: string;

    constructor(data: A) {
        Object.assign(this, data);
    }

    getName(): string {
        return this.name;
    }
}

(code in playground)

【讨论】:

  • 谢谢,这可能对我很有用。有什么办法可以摆脱idnameemail、..在class B中的重写?
  • 否,否则编译器会报错B无法实现A
猜你喜欢
  • 1970-01-01
  • 2017-01-12
  • 2014-01-23
  • 2016-09-17
  • 1970-01-01
  • 2012-04-22
  • 2020-09-19
  • 2016-11-30
  • 2011-02-12
相关资源
最近更新 更多