Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript 2.1 Custom Elements

TypeScript 2.1 Apparently now has support for writing custom html elements ("What's new in TypeScript - 2.1")

However I have been unable to find any documentation on how this is supposed to work.

Can anyone provide an explanation on how this is supposed to work, ideally with examples?

Thank You

like image 219
Zander Brown Avatar asked Dec 11 '16 11:12

Zander Brown


2 Answers

Currently this is not possible, when targeting ES5 with TypeScript. The Custom Elements API V1 needs ES6/ES2015-style classes. However if you target ES5 with TypeScript (for compatibility with IE 11 for example) all classes get transpiled to functions.

This is not a TypeScript limitation, but a limitation of the Custom Elements API V1 itself.

You have two options:

  1. Target ES2015 with TypeScript and thus drop IE11 support altogether
  2. Target ES5 with TypeScript and use:
    • a polyfill for the Custom Elements API, that supports ES5
    • a shim that allows the native Custom Element API to be used with ES5 (and thus transpiled TypeScript)

The release notes for TypeScript 2.1 are misleading; it is not a TypeScript issue at all. See this issue for more background.

like image 175
Christian Ulbrich Avatar answered Nov 05 '22 18:11

Christian Ulbrich


The only thing I can find on that page about custom elements is that the new way of handling super() calls in ES5 allows TypeScript to be used to define custom elements.

This just means that you can now write regular ES2015 code to define a custom element, and the new TypeScript compiler will output the correct ES5 code for it. Previously, the outputted code would not do the right thing with the super() call, which would break custom element classes.

There are no TypeScript examples for this, since this isn't really specific to TypeScript. It's just following the custom elements standard:

class MyCustomElement extends HTMLElement {
    constructor() {
        super();
        this.foo = "bar";
    }

    doSomething() {
        console.log(this.foo);
    }
}

customElements.define("my-custom-element", MyCustomElement);
like image 43
Mattias Buelens Avatar answered Nov 05 '22 18:11

Mattias Buelens