【问题标题】:TypeScript interface implementationsTypeScript 接口实现
【发布时间】:2013-01-08 11:45:50
【问题描述】:

我正在使用TypeScript 编写程序。问题是我实现了HTMLElement接口。

export class IEElement implements HTMLElement {
   // something here
}

编译器显示许多错误,我缺少一些属性(IEElement 声明了一个接口,但没有实现它)。我已经实现了大约 5 个我需要的属性。其余的都是多余的。如何避免错误?我需要实现所有接口成员吗?

【问题讨论】:

    标签: interface typescript


    【解决方案1】:

    是的,您需要实现所有非可选接口成员。

    接口是一个契约,如果您有一个实现该契约的类,您承诺实现该契约中的所有内容。

    HTMLElement 接口有很多实现 - 但如果您只是想添加一些行为,也许您可​​以从现有实现开始...

    interface SpecialElement extends HTMLElement {
        myCustomFunction: () => void;
    }
    
    var element = <SpecialElement>document.getElementById('example');
    
    element.myCustomFunction = function () { };
    

    【讨论】:

    • 这很糟糕:/ 现在我必须实现大约 70 个成员...感谢您的回答。祝你有美好的一天。
    • @Nickon 我刚刚为您添加了一个潜在的解决方案,它可能会让它更容易一些 - 取决于您在做什么!
    猜你喜欢
    • 2016-06-20
    • 2020-04-06
    • 2014-10-10
    • 2021-07-20
    • 2020-08-30
    • 1970-01-01
    • 2019-06-27
    • 2023-03-04
    • 2013-02-26
    相关资源
    最近更新 更多