Instantiating new HTMLElement in TypeScript
Note that the error you get here is "Illegal constructor". This is different from the error "object is not a function" that you would get if you were to write new {}()
, for example.
So, technically, HTMLDivElement
does have a constructor. It's just that this particular constructor throws an exception rather than creating an object.
Normally lib.d.ts
would just exclude such useless signatures, but TypeScript requires that the right-hand side of the instanceof
operator have a constructor. In other words, it's legal to write foo instanceof HTMLElement
, but not foo instanceof []
, and the difference is determined by the fact that HTMLElement
has a constructor.
There were basically three choices on the table here:
- Remove the construct signature from the DOM elements and remove the restriction on
instanceof
's right operand. This is undesirable because you'd really prefer to catch errors where someone accidentally writes code likex instanceof foo
instead ofx instanceof Foo
(wherefoo
is an instance ofFoo
). - Remove the construct signature from DOM elements, but keep the
instanceof
check in place. This is bad becausefoo instanceof HTMLElement
is a very reasonable thing to write. - The current situation, where the constructors exist but you have to know not to call them.
You can't construct DOM elements using normal constructors because you're supposed to go through document.createElement
. This is basically for technical reasons relating to how browsers implement these objects.
You have mistaken typescript syntax with c# syntax.
Just replace
var elem = new HTMLDivElement();
with one of the following
var elem = document.createElement('div');
or
var elem = <HTMLDivElement>(document.createElement('div'));
or
let elem = document.createElement('div') as HTMLDivElement
(if you need to use HTMLDivElement attributes)
If you extend HTMLElement
or any subclass like HTMLDivElement
You also need to register the custom element
class SampleDiv extends HTMLDivElement{
constructor(){
super();
}
}
customElements.define('sample-div', SampleDiv, { extends: 'div' });
See more here: https://javascript.info/custom-elements