Search code examples
typescriptpolymertypescript-typingspolymer-3.x

Typescript support for polymer v3


I am currently testing polymer 3 preview to see how to integrate it into our team workflow.

The recommended way to declare an element in v3 is:

import { PolymerElement } from '@polymer/polymer/polymer-element.js';
...
class MyElement extends PolymerElement {
  ...
}

See: https://www.polymer-project.org/blog/2018-03-23-polymer-3-latest-preview.html

This works well with typescript for basic things, but it does not understand that the class MyElement extends HTMLElement. So if I try to use this.dispatchEvent(...) in my code, the compilation will fail.

I tried to set a .d.ts to try to teach typescript but I could not get it to work. All those were pretty much unsuccessful.

1) Direct typing:

class PolymerElement extends HTMLElement{}

2) Typing the module:

declare module "polymer-element" {
    export class PolymerElement extends HTMLElement {}
}

And a few more variations but it never seem to be picked out by the transpiler. Any idas ?


Solution

  • I'm pretty sure you had to declare the module as "@polymer/polymer/polymer-element" instead of just "polymer-element", unless you added the typings directly to the path @polymer/polymer in your node_modules.

    Also, I'm not sure you're supposed to import polymer-element.js rather import polymer-element. The .js extension might interrupt adding the typings.