Can you extend a HTMLDivElement in TypeScript?

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);

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";

Really late to the show, but these days yet another approach is possible. Rather than adding fields to the interface HTMLDivElement one can create a new interface like

interface QuizElement extends HTMLDivElement {
  quizScore: number;
  ...
}

and then create QuizElement objects like

const quizzi: QuizElement = Object.assign(document.createElement("div"), {
  quizScore: 0,
  ...
});

Compared to other proposed approaches, this does not "pollute" HTMLDivElement with additional fields in the scope of QuizElement.


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';

Tags:

Typescript