Instantiating new HTMLElement in TypeScript

前端 未结 3 847
庸人自扰
庸人自扰 2021-02-04 23:44

I am trying to instantiate new HTMLDivElement in TypeScript

var elem = new HTMLDivElement();

but the browser throws

Uncaught T         


        
3条回答
  •  日久生厌
    2021-02-05 00:05

    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:

    1. 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 like x instanceof foo instead of x instanceof Foo (where foo is an instance of Foo).
    2. Remove the construct signature from DOM elements, but keep the instanceof check in place. This is bad because foo instanceof HTMLElement is a very reasonable thing to write.
    3. 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.

提交回复
热议问题