Can you extend a HTMLDivElement in TypeScript?

前端 未结 4 1214
名媛妹妹
名媛妹妹 2021-02-20 12:32

I am making a DOM based game for the first time. I would like to extend HTMLDivElement, however in TypeScript, HTMLDivElement is an Interface.

I would like to do this p

4条回答
  •  耶瑟儿~
    2021-02-20 13:17

    You can't extend HTMLDivElement because it isn't declared as a class. This makes sense, because the underlying native type doesn't make sense to extend.

    You have two alternative options.

    Option 1: Implements!

    Because HTMLDivElement is an interface, you can implement it...

    class QuizElement implements HTMLDivElement {
    

    You would have to implement all of the properties and methods of the interface. You probably don't want to do this.

    Option 2: Delegation.

    You can expose the specific properties and methods you want to make available on your QuizElement class and then delegate to an actual HTMLDivElement instance. Quick example below:

    class QuizElement {
        private element: HTMLDivElement;
    
        constructor(id: string) {
            this.element = document.getElementById(id);
        }
    
        set innerHTML(content: string) {
            this.element.innerHTML = content;
        }
    }
    
    var quizElement = new QuizElement('quiz');
    
    quizElement.innerHTML = 'Example';
    

提交回复
热议问题