Can you extend a HTMLDivElement in TypeScript?

前端 未结 4 1260
名媛妹妹
名媛妹妹 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:14

    Also you can 'extend' the HTMLDivElement interface with data members if you wish, not by using extends since it is not a class, but by adding it via the interface. TypeScript interfaces are 'open ended', see page 85 of the spec under 'declaration merging'.

    http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

    for example, the below adds the member 'mydata' of type string to the HTMLDivElement interface.

    interface HTMLDivElement {
    
        mydata : string;
    
    }
    
    // now we can assign a value
    
     var div = <HTMLDivElement>document.getElementById("myDiv"); 
    
     div.mydata = "test";
    
    0 讨论(0)
  • 2021-02-20 13:15

    A bit late, but apparently it's still not possible to extend HTMLDivElement. A simple way to solve extending a DIV: just use CSS to make a generic HTMLElement behave like a div.

    CSS

     my-element {
        display:block;
     } 
    

    Javascript

    class MyElement extends HTMLElement{
      constructor(){
          super()
          this.innerHTML = "I behave exactly like a div"
      }
    }
    
    window.customElements.define('my-element', MyElement);
    
    0 讨论(0)
  • 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 = <HTMLDivElement>document.getElementById(id);
        }
    
        set innerHTML(content: string) {
            this.element.innerHTML = content;
        }
    }
    
    var quizElement = new QuizElement('quiz');
    
    quizElement.innerHTML = 'Example';
    
    0 讨论(0)
  • 2021-02-20 13:25

    It is not the best way but it works.

    function MyElement(){
      var element = document.createElement("div");
    
      element.viewInner = function(){
        console.log(this, this.innerHTML)
      };
    
      return element;
    }
    
    var test = new MyElement();
    test.innerHTML = "Hi";
    test.viewInner(); // <div> Hi
    
    0 讨论(0)
提交回复
热议问题