Search code examples
typescriptecmascript-6web-componentcustom-element

Why can't ES2015 classes be reliably transpiled in TypeScript?


I recently stumbled over the following statement on MDN:

Please note that ES2015 classes cannot reliably be transpiled in Babel 6 or TypeScript targeting legacy browsers. You can either use Babel 7 or the babel-plugin-transform-builtin-classes for Babel 6, and target ES2015 in TypeScript instead of legacy.

Is this statement just outdated for TypeScript > 3.x.x or could anyone explain what shortcomings there are for TypeScript transpilation?

I didn't notice problems when setting target to ES5 in tsconfig.json, besides having to polyfill some more functionality (as expected).

Understanding those problems if they exist, would be really helpfull when dealing with custom elements and web components.


Solution

  • As explained in the Github page of the Custom Element polyfill, Custom Elements are defined as extensions of the HTMLElement class, which require a new ES6 feature that cannot be perfectly emulated with ES5 Javascript: super()/Reflect.construct():

    The spec requires that an element call the HTMLElement constructor. Typically an ES5 style class would do something like HTMLElement.call(this) to emulate super(). However, HTMLElement must be called as a constructor and not as a plain function, i.e. with Reflect.construct(HTMLElement, [], MyCEConstructor), or it will throw.