Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 为什么我要重写所有成员来实现接口?_Oop_Inheritance_Typescript_Interface - Fatal编程技术网

Oop 为什么我要重写所有成员来实现接口?

Oop 为什么我要重写所有成员来实现接口?,oop,inheritance,typescript,interface,Oop,Inheritance,Typescript,Interface,我有一个带有一些可选变量的接口,如: interface A { id: string; name?: string; email?: string; ... } 我想做的是 class B implements A { constructor(x: string, y: string, ...) { this.id = x; this.name = y; ... } getName():

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

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;
    }
}
我不想重写我将使用的所有成员,我需要一些成员保持可选。每个接口将只使用一个类实现,因此如果我重写
类B
中的所有成员,那么
接口A
将变得无用

您可能会问“为什么您需要
接口A
?”。我需要它,因为我正在从其他项目使用它,我必须
扩展
用一些函数实现它

关于这个实现有什么解决方案或不同的想法吗

一个选项是这样使用:


()

谢谢,这可能对我很有用。难道没有办法摆脱重写
id
name
email
,。。在
类B
中?否,否则编译器将抱怨
B
未能实现
A
您可以使用基类而不是接口(A),并使用
类B扩展A
。在这种情况下,您不需要在BI中声明所有这些成员,也不应该更改
接口A
,它是由另一个开发人员提供给我的。在这种情况下,您必须实现它。。
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;
    }
}