Zander Brown
Zander Brown

Reputation: 637

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

Upvotes: 9

Views: 9503

Answers (3)

Christian Aberger
Christian Aberger

Reputation: 1

Forget IE11 and use es6 (https://caniuse.com/?search=es6). All you have to do is to change the target line in your tsconfig.json to:

//tsconfig.json
{
  "compilerOptions": {
    "target": "es6",
  }
}

To learn more about this file see: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

Upvotes: 0

Christian Ulbrich
Christian Ulbrich

Reputation: 3574

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.

Upvotes: 5

Mattias Buelens
Mattias Buelens

Reputation: 20179

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

Upvotes: 5

Related Questions