TypeScript Support
Since Release 6.9 you can scaffold TypeScript based Polymer client in Studio. When creating Polymer client module you will be able to select polymer2-typescript
preset of the client. Main differences with basic JavaScript version:
- Component classes are placed in separate
*.ts
files -
myapp-component.ts
namespace myapp { const {customElement} = Polymer.decorators; @customElement('myapp-component') class MyappComponent extends Polymer.Element { } }
myapp-component.html<link rel="import" href="../bower_components/polymer/polymer.html"> <link rel="import" href="./shared-styles.html"> <dom-module id="myapp-component"> <template> <!-- some html markup --> </template> <script src="myapp-component.js"></script> </dom-module>
- There is an additional phase of build process - TypeScript compilation
-
See
scripts
section ofpackage.json
{ "scripts": { "build": "npm run compile && polymer build", "compile": "tsc", "watch": "tsc -w" } }
Now before
polymer build
there isnpm run compile
command which effectively runs TypeScript compilation (tsc
).If you change the source code of component classes and expect your changes to be picked by Studio’s hot deploy you should manually run
npm run watch
command inmodules/front
directory.
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 definestatic get is()
method and manual invocation ofcustomElements.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.