Support for Typescript in Polymer version 3

Currently experimenting with Polymer 3 preview to explore how it can be integrated into our team workflow.

The recommended method for declaring an element in v3 is as follows:

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

For more information, visit: https://www.polymer-project.org/blog/2018-03-23-polymer-3-latest-preview.html

While this approach works smoothly with typescript for basic functionalities, it does not recognize that the class MyElement extends HTMLElement. As a result, attempting to use this.dispatchEvent(...) in the code will lead to compilation errors.

I attempted to create a .d.ts file to instruct typescript, but all attempts were unsuccessful.

1) Trying direct typing:

class PolymerElement extends HTMLElement{}

2) Typing the module:

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

Despite trying several variations, the transpiler does not seem to recognize any of them. Any suggestions?

Answer №1

Starting from version 3.0.5, TypeScript declarations are now included within the core @polymer/polymer NPM package itself. Additionally, TypeScript declarations are also available for elements such as iron-, paper-, and others starting from version 3.0.0.

import {PolymerElement, html} from '@polymer/polymer';

class MyElement extends PolymerElement {
  static get template() {
    return html`<p>Hello [[who]]</p>`;
  }
  static get properties() {
    return {
      who: String,
    };
  }
  who = 'World';
}
customElements.define('my-element', MyElement);

Furthermore, you have the option to utilize the @polymer/decorators package for enhanced type safety and a more streamlined syntax:

import {PolymerElement, html} from '@polymer/polymer';
import {customElement, property} from '@polymer/decorators';

@customElement('my-element')
class MyElement extends PolymerElement {
  static get template() {
    return html`<p>Hello [[who]]</p>`;
  }
  @property({type: String})
  who = 'World';
}

Answer №2

It is important to declare the module as

"@polymer/polymer/polymer-element"
instead of just "polymer-element", unless you have included the typings directly in the path @polymer/polymer within your node_modules.

Furthermore, make sure to import polymer-element instead of polymer-element.js. Using the .js extension could cause issues with adding the typings properly.

Answer №3

At this moment, it appears that v3 does not yet fully support TypeScript typings.

You may notice a recent commit in the v3.x branch titled Delete typings for now..

Possible solutions:

1. Tell TypeScript to temporarily ignore the lack of typings:

class MyElement extends PolymerElement {
  fn(){
     (this as any).dispatchEvent(...) 
  }
}

2. Have your element explicitly extend from HTMLElement:

class MyElement extends PolymerElement, HTMLElement {
    fn() {
        this.dispatchEvent(...)
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I display options in a react autocomplete feature?

Using the autocomplete component from @material-ui/lab/autocomplete, I am trying to retrieve the title_display result in the options field. These results are being fetched from an API using axios. You can view my code here--> https://codesandbox.io/s/r ...

Ways to bypass browser pop-up blockers when using the window.open function

I am displaying an HTML retrieved from the backend. printHtml(htmlContent) { var windowToPrint = window.open('', '_blank'); windowToPrint.document.write(htmlContent); setTimeout(function () { windowToPrint.document ...

Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks. Following guidance from this source, I successfully implemented syntax highlighting wit ...

Displaying user input data in a separate component post form submission within Angular

I recently developed an employee center app with both form and details views. After submitting the form, the data entered should be displayed in the details view. To facilitate this data transfer, I created an EmployeeService to connect the form and detail ...

Heroku: Unable to retrieve resource - server returned a 404 (Not Found) status code

I successfully developed my Angular 6 app on my local machine with everything working perfectly. However, after deploying the project to Heroku and running my app here Testing App, I encountered an error in the console browser. Failed to load resource: ...

Setting up Storybook with Tailwindcss, ReactJS and Typescript: A comprehensive guide

What is the best way to configure Storybook to handle Tailwindcss styles and absolute paths? Just a heads up, this question and answer are self-documenting in line with this. It was quite the process to figure out, but I'm certain it will help others ...

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

How to dynamically incorporate methods into a TypeScript class

I'm currently attempting to dynamically inject a method into an external class in TypeScript, but I'm encountering the following error. Error TS2339: Property 'modifyLogger' does not exist on type 'extclass'. Here's the ...

Having trouble processing images in multi-file components with Vue and TypeScript

Recently, I reorganized my component setup by implementing a multi-file structure: src/components/ui/navbar/ Navbar.component.ts navbar.html navbar.scss Within the navbar.html file, there was an issue with a base64-encoded image <img /> ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

TypeScript incorporates a variety of @types versions for react

I made changes to my compilerOptions within the tsconfig.json file with the specified paths "paths": { "react": ["node_modules/@types/react"], "@types/react": ["node_modules/@types/react"] } However, I noticed that @types/react-router is using its o ...

A mistake has occurred: Unhandled promise rejection TypeError: Unable to assign the property 'devices' to an undefined object in Ionic 4 with Angular

Within my MyDevicesPage class, I am attempting to manipulate the res object and then pass it to the updateDevicesToServer method of DataService for further actions. The code compiles without errors, but at runtime, an error is thrown: ERROR Error: Uncaught ...

Having issues with Craco not recognizing alias configuration for TypeScript in Azure Pipeline webpack

I am encountering an issue with my ReactJs app that uses Craco, Webpack, and Typescript. While the application can run and build successfully locally, I am facing problems when trying to build it on Azure DevOps, specifically in creating aliases. azure ...

What would be the optimal type for the second argument of the `simulate` method?

When using the simulate function, I am familiar with code like this: simulate("change", { target: { value: '7' } }); However, if my onChange function requires an object as a parameter, what should I pass in the second argument? interface myObj ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

Attempting to leverage the combination of mocha, ES6 modules, and ts-node while utilizing the --experimental-loader option

I've been attempting to make the ts-node option --experimental-loader function alongside mocha, but so far I haven't had any success. Before I started compiling ES6 modules, running mocha tests was as simple as: "test": "nyc --reporter=html mocha ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...