【问题标题】:typescript implementing interfaces in classes and assigning it to a object with a type interfacetypescript 在类中实现接口并将其分配给具有类型接口的对象
【发布时间】:2019-02-06 15:14:58
【问题描述】:

我是打字稿的新手,遇到了实现接口的类。我知道一个类可以添加接口没有的属性,但它必须包含接口具有的所有属性。我的问题是当我从我的类中创建一个具有某种接口类型的新对象时,它会变得混乱。 我在辅导老师的网站上看到,如下代码

   interface IPerson {
        name: string;
        display():void;
    }

    interface IEmployee {
        empCode: number;
    }

    class Employee implements IPerson, IEmployee {
        empCode: number;
        name: string;

        constructor(empcode: number, name:string) {
            this.empCode = empcode;
            this.name = name;
        }

        display(): void {
            console.log("Name = " + this.name +  ", Employee Code = " + this.empCode);
        }
    }

    let per:IPerson = new Employee(100, "Bill");
    per.display(); // Name = Bill, Employee Code = 100

    let emp:IEmployee = new Employee(100, "Bill");
    emp.display(); //Compiler Error: Property 'display' does not exist on type IEmployee'

如果在let per:IPerson = new Employee(100, "Bill"); 我会console.log(per.empCode) 之后会有一个编译器错误提示

类型“IPerson”上不存在属性“empCode”。

那么为什么 per.display() 即使类型是没有 empCode 属性的 Iperson amd 也会设法记录 empCode。请您帮我理解其中的区别

【问题讨论】:

    标签: typescript class interface interface-implementation


    【解决方案1】:

    这是面向对象编程语言的标准行为。基本上当你这样做时:

    let per:IPerson = new Employee(100, "Bill");
    

    编译器只关心per 的类型,即IPersonIPerson 没有属性 empCode。即使我们知道它是一个 Employee 并且它确实有一个 empCode 属性,编译器也无法确定这一点!

    当您执行per.display() 时,empCode 是可访问的,因为此时您将处于Employee 类的范围内。

    【讨论】:

    • 同意答案。另一个建议是添加IPerson + IEmployee。即:interface IPersonEmployee { name: string; display():void; empCode: number; } ..... let per:IPersonEmployee = new IPersonEmployee(100,'Bill', 200);
    • @AlbertoAM 不会通过再次重新定义属性来创建“合并”接口。只需:interface IPersonEmployee extends IPerson, IEmployee {}。您的代码示例也被破坏:您无法像在此处那样实例化接口。这是接口的基本属性。
    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2021-07-31
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2021-07-20
    • 2022-01-15
    • 2012-03-24
    相关资源
    最近更新 更多