Customize Typing for Properties in Subclasses of Lit-Element Using TypeScript

When extending a lit-element Class to add more specific typing, should the @property decorator be overridden or just the type and initializer? For example, consider the following code:

interface AB {
   a: number,
   b: string,
}

@customElement('my-parent')
class MyParent extends LitElement {
    @property({type: Array}) stuff: readonly any[] = [];
}

which of the following approaches is the correct way to subclass:

@customElement('my-child')
class MyChild extends MyParent {
    override @property({type: Array}) stuff: readonly Readonly<AB>[] = [];
}

or

@customElement('my-child')
class MyChild extends MyParent {
    override stuff: readonly Readonly<AB>[] = [];
}

Both are currently functioning in my project, so I am unsure which one to use as the standard.

Answer №1

It's interesting that both syntaxes seem to work, which may be a quirk of TypeScript's original implementation of class fields with useDefineForClassFields: false. This results in "overridden" class fields still invoking the accessor added by the decorator on a superclass field.

However, semantically it would make more sense for overridden properties to be decorated separately and not inherit previously decorated behavior. In this case, using @property in both the base and subclass will be the only approach that works when utilizing standard decorators for Lit reactive properties, requiring the inclusion of the accessor keyword to turn class fields into accessors.

For further details, particularly regarding the repercussions for existing code using inheritance, refer to the TypeScript 3.7 Announcement, specifically the section discussing how set accessors from base classes won't be triggered and will be completely overwritten.

Keep in mind that useDefineForClassFields is set to true by default if the lib includes "es2022" or later versions, as well as "esNext".


Below is an outdated version of my response which contained inaccurate information.

It's peculiar to use @property on a readonly item since the purpose of @property is to enable reactivity for updates upon setting, something readonly implies you wouldn't do.

In any event, overriding a class property in a subclass without @property will eliminate its reactivity.

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

Sending data through URL links in HTML

$.post("/diabetes/ropimages/getcount.php",{patientId:$("#patient_id").val()} ,function(data1){ //alert(data1); var count = data1; var patientId = $("#patient_id").val(); var reportId; for( var i = 1 ; i <= count ; i++) { var imageLink =&a ...

"Learn how to efficiently incorporate data into data-binding in VUE JS with just a

In my data binding, there is a string that reads as follows: bc-men,bc-men-fashion,bc-men-underwear I want to create an input field where I can enter "bc-some-category", click "Add", and have it appended to the end of the list with a comma in front. Her ...

Is it possible to invoke Bootstrap modal functions without using jQuery?

I'm in the process of removing jQuery dependencies from my app, but I still rely on Bootstrap. Is there a way to trigger modal functions like $('#myModal').modal('show') without using jQuery now? ...

Transform text into clickable URL references

I have developed a unique component in NextJS that transforms a specified string within a text into a link of my choosing. export const StringToLink = ({ href, initialText, stringToReplace, useAnchorTag = false, }: { initialText: string; string ...

Challenges with resizing windows in jQuery

I'm currently working on optimizing my jQuery code and everything seems to be running smoothly so far: jQuery $(document).ready(function(){ $(".fadeinbg").click(function(){ $("#content").fadeIn(); }); var height = $(window).height() ...

Retrieve a selection of data from the data.json file and mix it up

My webpage has a json data sheet containing multiple objects that I am currently showcasing. { "objects": [ ... ] } In terms of templating: $(function () { $.getJSON('data.json', function(data) { var template = $('#objectstpl') ...

Why does clicking to add to an existing array only result in the array being cleared instead?

Need help with an AngularJS question relating to scope binding and click events. I want to add one value on the first click and another value on the second click, but it's only returning an empty array and filling the first value again. Why is that ha ...

Creating a sliding bottom border effect with CSS when clicked

Is there a way to animate the sliding of the bottom border of a menu item when clicked on? Check out the code below: HTML - <div class="menu"> <div class="menu-item active">menu 1</div> <div class="menu-item">menu 2</ ...

Learn the process of adding a key and value into an array using Angular

I need to filter data based on the number of rows and columns provided by the user. After reading an excel file, I extract the data in the controller: https://i.sstatic.net/vPpxL.png These are the column headers retrieved after the user entered 5 as the ...

Experiencing a type error within Redux in a React Native project utilizing TypeScript

I am currently working on implementing a feature to store the boolean value of whether a phone number is verified or not. Within my login component: await dispatch(setOTPVerified(data.is_phone_verified)); Action.tsx: export const OTP_VERIFIED = 'OTP ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

The animation feature of the jQuery toggle method is not functioning as expected

In this HTML snippet, I have a JQUERY script that toggles elements with "red" and "green" classes. The code works but without any animation! I want to toggle them in a "slow" mode. I've tried using the animation method too, but it's not working. ...

Bizarre Object notation with JavaScript

While browsing through a Library called WebApp.net, I stumbled upon this interesting piece of code: var $h = { get HEAD() { return 0 }, get BACK() { return 1 }, get HOME() { return 2 }, get LEFT() { return 3 }, get RIGHT() { return 4 } ...

The tooltip being displayed is plain and lacks any design elements

When I hover over my a element, only a simple tooltip appears without any styling, unlike what is shown in the Bootstrap documentation. (I am creating the a element using JavaScript) HTML <!DOCTYPE html> <html lang="en"> <head> ...

The controller returned a null value

I've encountered a situation where I'm utilizing a service file to execute a stored procedure: function createCampaign($campaignName, $groupNumber){ $stmt = \DB::connection('odbc')->getPdo()->prepare('CALL SCHE ...

Creating a CSS triangle that smoothly transitions between two different colors

Is it possible to create a triangle in CSS that smoothly transitions between two colors without relying on a hover state? .arrow-down { width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; b ...

Retrieve information dynamically from a JSON file using the get JSON function and iterate through the data

I possess a JSON file that I wish to utilize in creating dynamic HTML elements with the JSON content. Below is the provided JSON data: { "india": [ { "position": "left", "imgurl":"3.jpg" }, { ...

Masonry.js is working perfectly in Firefox, however, it is experiencing compatibility issues with Chrome and

Recently, I encountered a strange issue with Dessandro's Masonry.js library. It was working perfectly fine until it suddenly stopped functioning in Safari and Chrome (I haven't tested it on IE yet), while still working flawlessly in Firefox. Usua ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...

Only display the parent component in React if there are children components that will be rendered

Navigating this situation in React has me puzzled. Within a group of tabs, I have several chart components that render based on their permission prop. If the user lacks access to a chart, it won't be displayed - straightforward enough. However, I&ap ...