3.7.3.7.1. Create Polymer Components with TypeScript

TypeScript decorators by Polymer team provide more convenient and less verbose way to create component classes. Let’s look at the following example:

/// <reference path="../bower_components/cuba-app/cuba-app.d.ts" />
/// <reference path="../bower_components/app-layout/app-drawer/app-drawer.d.ts" />
/// <reference path="../bower_components/app-layout/app-drawer-layout/app-drawer-layout.d.ts" />

namespace myapp {

  // Create shortcuts to decorators
  const {customElement, property, observe, query} = Polymer.decorators;

  @customElement('myapp-component')
  class MyappComponent extends (Polymer.mixinBehaviors([CubaAppAwareBehavior, CubaLocalizeBehavior], Polymer.Element) as
    new () => Polymer.Element & CubaAppAwareBehavior & CubaLocalizeBehavior) {

    @property({type: Boolean})
    enabled: boolean;

    @property({type: String})
    caption: string;

    @query('#drawer')
    drawer: AppDrawerElement;

    @observe('app')
    _init(app: cuba.CubaApp) {
      ...
    }

    @computed('enabled', 'caption')
    get enabledCaption() {
      ...
    }
  }
}
  • /// <reference path="…​"/> - allows you to import TypeScript declarations of other elements or libraries.

  • @customElements('element-name') decorator eliminates necessity to define static get is() method and manual invocation of customElements.define().

  • @property() decorator allows you to specify component’s properties.

  • @query('.css-selector') decorator allows you to select DOM elements of your component.

  • @observe('propertyName') decorator allows you to define property observers.

  • @computed() decorator allows you to define computed methods.

See polymer-decorators github repository for more examples.