【问题标题】:Typescript - Base an interface from a classTypescript - 基于类的接口
【发布时间】:2016-02-03 00:45:27
【问题描述】:

由于私有属性 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);

【问题讨论】:

    标签: interface typescript polymorphism


    【解决方案1】:

    在 TypeScript 中,可以在定义接口的同时“扩展”一个类,在这个接口中,您将拥有扩展类的所有成员,包括私有、公共和受保护的。

    尝试这样做:

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

    但是,TypeScript 在幕后“知道”这个接口有一些私有成员,这就是为什么它会告诉你 "IA" 上缺少 "e2" 属性强>。

    如果你实现 "I" 你必须考虑到这一点,就像你会扩展 "A" (具有私有成员)

    【讨论】:

    • 感谢 Gilamran 的提示。我修改代码如下,它可以工作。
    【解决方案2】:
    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);
    

    【讨论】:

      猜你喜欢
      • 2016-12-30
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 2021-12-03
      • 2021-10-27
      • 2016-03-24
      • 1970-01-01
      • 2019-09-21
      相关资源
      最近更新 更多