Using an array of custom TypeScript types or objects as a property in Lit v2

I am seeking to convert my existing JavaScript CustomElements/WebComponents (created with Lit v1 and later migrated to v2) into TypeScript.

For instance:

export class MyElement extends LitElement {
  ...
  @property({type: String})
  name = 'World';
  ...
}

... or you can check this example out: https://github.com/lit/lit-element-starter-ts/blob/main/src/my-element.ts#L37

Is there a way for me to declare a property as an array of my custom TypeScript classes?

For example, like this:

export class MyElement extends LitElement {
  ...
  @property({type: Array<MyCustomClass>})
  customClassArray = [];
  // or: customClassArray = [new MyCustomClass("foo")]; 
  ...
}

Answer №1

When working with Lit, the @property decorator plays a key role in creating reactive properties and ensuring that the attribute value is reflected accurately (especially if reflect: true is enabled). However, handling non-string values, such as numbers or booleans, can be tricky. Numbers need to be parsed correctly, and for booleans, the mere existence of the attribute indicates a value of true.

To tackle this issue, Lit introduces the concept of type, which allows you to specify the appropriate converter for attribute values. Think of it as specifying a type hint or conversion type for attribute/value transformations. For reference, you can check out Lit's default converter.

It is important to define your actual types in TypeScript when using Lit.

export class YourElement extends LitElement {
  @property({ type: Array })
  customClassArray = new Array<YourCustomClass>();
  // or: customClassArray = [new YourCustomClass()];
}

Answer №2

I have come up with a solution on my own that is quite similar to what @arshia11d suggested.

import { MyCustomClass } from './MyCustomClass';    

export class MyElement extends LitElement {
      @property({ type: Array }) //Array<MyCustomClass> throws ts(2303) error
      annotations: MyCustomClass[] = [];
    }

Here is the type definition:

export interface IMyCustomClass {
  label: string;
}

export class MyCustomClass implements IMyCustomClass {
  label: string;

  constructor(
    _label: string
  ) {
    this.label = _label;
  }
}

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

Fixing the "Module not found" error in an Angular library using npm link

I'm currently working on creating an Angular wrapper for a Javascript library, but I've encountered a "Module not found" error. The Javascript library is still in development and has not been published to NPM yet. To work around this issue, I hav ...

Tests with Protractor are guaranteed to pass as long as the specification is within a loop

ISSUE : While using the code provided in the EXAMPLE section, the expect block inside the forEach loop always passes, which is not the expected behavior. For instance, here is a scenario along with a screenshot of the test report: expect('bt bt-p ...

Selecting ion-tabs causes the margin-top of scroll-content to be destroyed

Check out the Stackblitz Demo I'm encountering a major issue with the Navigation of Tabs. On my main page (without Tabs), there are simple buttons that pass different navparams to pre-select a specific tab. If you take a look at the demo and click t ...

How to Merge Items within an Array of Objects Using Typescript?

I'm currently facing a challenge in combining objects from an array of Objects in typescript. The structure of the array is as follows: 0: {type: 'FeatureCollection', features: Array(134)} 1: {type: 'FeatureCollection', features: ...

Unable to utilize my TypeScript library within JavaScript code

I've hit a roadblock with a seemingly straightforward task and could really use some fresh perspective. I'm currently developing a custom TypeScript library intended for use in both TypeScript and JavaScript projects within our organization. Th ...

One method for identifying which observable has been altered in Observable.merge is by examining the output of

Here is a simplified and clear version of my code: connect(): Observable<Customer[]> { const displayDataChanges = [ this._customerDatabase.dataChange, this._filterChange, this._sort.mdSortChange, this._paginator.page ]; ...

How can you obtain the user ID by verifying an email when using applyActionCode in Firebase 9 modular?

Is there a way to access the UID of an email verified user? Will the response provide any helpful insights, or should I handle this from another source? const handleVerifyEmail = (auth: any, actionCode: any) => { applyActionCode(auth, actionCode! ...

The transformation of Typescript into void for Observables

I am facing a situation where I have a class structured like this: class Consumer { consume(event: Observable<void>) { event.subscribe(() => console.log('Something happened')); } } The issue arises when my source observable is ...

Automating the scrolling function in Angular 2 to automatically navigate to the bottom of the page whenever a message is sent or opened

In my message conversation section, I want to ensure that the scroll is always at the bottom. When the page is reopened, the last message should be displayed first. HTML: <ul> <li *ngFor="let reply of message_show.messages"> ...

Having Trouble Displaying Material UI Icons in Your React App? Here's Why: "Invalid Objects as React Children"

I have been working on a basic app that showcases information about a patient. In this specific component, I am only displaying the name, occupation, and a symbol from Material UI to indicate whether the patient is male or female. However, when I attempt ...

Compiling TypeScript files into multiple JavaScript files using Visual Studio 2015 Update 1

I am working on a project that involves multiple Typescript files and I am trying to find a way to compile specific groups of these files into separate JS files. For example: Scripts\Group1\file1.ts Scripts\Group1\file2.ts Scripts&bso ...

In an array where the first 3 images have been filtered using an if statement, how can I show the image at the 3rd index (4th image) starting from the beginning?

In my personal web development project, I'm using AngularJS for the front-end and .NET Core for the back-end to create a website for a musical instrument retailer. The model I'm working with is called "Guitar" and all the guitar data is stored in ...

Typescript - optional type when a generic is not given

I am hoping for optionalFields to be of type OptionalFieldsByTopic<Topic> if a generic is not provided, or else OptionalFieldsByTopic<T>. Thank you in advance for the assistance. export interface ICreateItem<T extends Topic = never> { // ...

Setting the resolve signature in IDialogOptions using TypeScript with the $mddialog service of Angular Material is an important feature to understand

At the moment, the IDialogOptions resolve signature is as follows: resolve? : ng.IPromise<any> However, based on the documentation, it should also be able to accept functions that return a promise. Therefore, I have modified it to the following str ...

incorporating a personalized HTMLElement using Typescript

Hey there! I'm fairly new to using Angular and could use some help. I'm trying to insert a custom HTML element onto a page when a button is clicked, but I'm struggling to figure it out. Here are my HTML and TypeScript files: TypeScript Fil ...

What steps can be taken to fix a Node.js startup issue with New Relic caused by an error message stating: "Error: Failed to establish a connection

Recently, I cloned a fully functional repository. This project is in Typescript and I am now working on adding some unit tests using mocha. However, upon running the project, an error related to NewRelic pops up: PS C:\Users\ENV\Projects ...

Is it possible for me to incorporate a new feature into a library that operates using its unique interface?

I'm currently utilizing the angular-gridster2 library and I am looking to add two additional properties in the gridsterItem interface to hold some specific values. How can this be achieved? Despite creating an extended interface of their own, the pack ...

Encountering a NullInjectorError in Angular while utilizing dynamic module federation when importing a standalone component along with

My main goal is to develop a shell application acting as a dashboard without routing, featuring multiple cards with remote content (microfrontend standalone component). I have been following a tutorial that aligns closely with my requirements: . The reas ...

The function yields a resolved promise rather than returning data

I'm trying to use this function: const fetchAndMapData = (): Promise<Data> => { const data = fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then((items) => items.map((item: ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...