Typescript - 基于类的接口

时间:2015-11-03 00:17:06

标签: interface typescript polymorphism

由于私有属性e1,以下代码会生成错误。我想知道e1是否是接口I的一部分。我认为接口是关于公共元素的。我是否知道如何修复代码以使其工作(或如何在具有私有属性的类上建立接口。

感谢您的帮助,

安德烈

class A {
        constructor(private e1: string, public e2: string) {}
    public displayValue(): string {
        return this.e1 + ":" + this.e2;
    }
}

interface I extends A {
    e3: string;
    displayValue2(): string;
}

class IA implements I {
    constructor(public e2: string, public e3: string, private e4: string) {}

    public displayValue(): string {
        return this.e2 + ":" + this.e3 + ":" + this.e4;
    }

    public displayValue2(): string {
        return "testing";
    }
}

var f: (a: A) => void = function(a: A) {
    console.log(a);
}

var a1: A = new A("teste1", "teste2");
var a2: IA = new IA("testiae2", "testiae3", "testiae4");

f(a1);
f(a2);

2 个答案:

答案 0 :(得分:0)

在TypeScript中,可以"扩展"定义接口时的类,在此接口中,您将拥有扩展类中的所有成员,包括private,public和protected。

尝试这样做:

var i: I;
i. // <-- The IDE will show you ONLY the public members of I, but will know about the privates

但是,在幕后TypeScript&#34; Knows&#34;这个界面有一些私人成员,这就是为什么它会告诉你&#34; IA&#34; 上缺少&#34; e2&#34; 属性

如果您实施&#34;我&#34; ,您必须考虑到这一点,就像您要扩展&#34; A&#34; (有私人会员)

答案 1 :(得分:0)

class A {
    constructor(private e1: string, public e2: string) {}
    public displayValue(): string {
        return this.e1 + ":" + this.e2;
    }
}

interface I extends A {
    e3: string;
    displayValue2(): string;
}

var i: I;

class IA extends A implements I {
    constructor(public e3: string, private e4: string, e1: string, e2: string) {
        super(e1, e2);
    }

    public displayValue(): string {
        return this.e2 + ":" + this.e3 + ":" + this.e4;
    }

    public displayValue2(): string {
        return "testing";
    }
}

var f: (a: A) => void = function(a: A) {
    console.log(a);
    console.log(a.displayValue());
}

var a1: A = new A("teste1", "teste2");
var a2: IA = new IA("testiae2", "testiae3", "testiae4", "testiae1");

f(a1);
f(a2);
相关问题