Is it possible to utilize super class methods as decorator methods in Typescript?

I'm working on a project where I aim to create an easily extendible decorator factory, and achieving this would be a great accomplishment.

The main goal is to utilize the methods of a superclass as decorators for properties in subclasses.

This is typically how decorators are used:

import { handleSavePropertyNameDecorator } from "./W-ODecorator"

class Main {
    @handleSavePropertyNameDecorator
    test1: string = ""
}

export default Main

Here is the code snippet for the decorator function:

const propertyNames = [];

export const handleSavePropertyNameDecorator = (_instance: any, propertyName: string) => {
    console.log("Executing handleSavePropertyNameDecorator")
    propertyNames.push(propertyName);
}

Instead of creating a separate function for the decorator, my goal is to have the decorator function inherited from the superclass:

import SuperClass from "./SuperClass"

class Main extends SuperClass{
    @this.handleDecoratorFunction
    test1: string = ""
}

export default Main
class SuperClass {
    static propertyNameArray: string[] = [];

    protected handleDecoratorFunction(_instance: any, propertyName: string) {
        console.log("executing handle decorator function from super class!")
        SuperClass.propertyNameArray.push(propertyName);
    }
}
export default SuperClass;

There is currently an issue with the keyword "this" triggering a compilation error due to possible undefined value. The decorator function is not being executed when I run the code.

Is there a workaround or alternative approach to make this idea feasible? Implementing this feature would greatly benefit the organization of my project.

Thank you for your assistance!

Answer №1

Sorry, it's not possible to execute the decorator at the time of instantiation as it is only applied during class definition. This means that instance methods from your superclass won't be accessible.

However, you can achieve this using a static method:

class SuperClass {
    static propertyNameArray: string[] = [];

    protected static handleDecoratorFunction(_instance: any, propertyName: string) {
        console.log("Executing the handle decorator function from the super class!")
        this.propertyNameArray.push(propertyName);
    }
}

class Main extends SuperClass{
    @SuperClass.handleDecoratorFunction
    test1: string = ""
}

export default Main

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

Problem with JQuery Dialog Box and Div

Within my HTML I have a div labeled "passage-content". This div's text is meant to be displayed in a jQuery dialog box when a button is clicked, however the content of the div is constantly changing due to the dynamic nature of the page. Each time the ...

Encountering numerous instances of blocking scoped variables being redeclared in @types library files

I'm encountering multiple TS errors from leaflet and leaflet-editable @types that are all showing the same error but pointing to different lines in the type definition files: TS2451: Cannot redeclare block-scoped variable 'L'. My project ...

The password reset feature using bcrypt is malfunctioning, as headers cannot be modified once they have been sent to the client

After developing a reset password function, the code appears as follows: router.get('/reset/:id',function(req,res,next){ User.findOne({'resetToken': req.params.id.trim()}) .exec(function(error, user){ if (error) ...

Struggling to navigate with react-semantic-ui and router

Here is a sample code snippet for a simple menu/header using JSX: <Menu fixed='top' inverted> <Container> <Menu.Item header>Simple Blog</Menu.Item> <Menu.Item name='home' as={Link} to=&ap ...

I am unable to transmit information using the `http.post` function

When attempting to send a post request to the backend, I am receiving a response code of 500 and an empty data object on the API side. Interestingly, using Postman gives successful results. return http.post(link,data,headers).subscribe(response=>{ ...

Stop the use of JavaScript to control the browser's back button in an ASP.NET environment

I have encountered an issue where a JavaScript code called from the server side works fine initially. However, when the user navigates back to the page using the browser's back button, the JavaScript code (specifically ScriptManager.RegisterStartupScr ...

Click on the nearest Details element to reveal its content

Is there a way to create a button that can open the nearest details element (located above the button) without relying on an ID? I've experimented with different versions of the code below and scoured through various discussions, but I haven't be ...

Surprising pause in the menu transition animation

Currently, I am in the process of developing a menu that seems to have some flaws. One issue is that it appears a bit choppy, but the more concerning problem is the half-second delay after clicking an item before it animates. The concept behind this menu ...

A step-by-step guide on displaying log files using NanoHTTPD

I have developed a Java desktop application that can receive HTTP requests using the embedded NanoHTTPD web server from https://github.com/NanoHttpd/nanohttpd. Once an HTTP request is received, my application performs certain tasks and logs the activity to ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Learn how to dynamically modify the text and color of a column value within a <v-data-table> component in Vue.js 2.6.11 and Vuetify 2.2.11 based on a specific condition

In my current project where I am developing a web application using ASP.NET CORE for the backend and vue.js for the frontend, I encountered an issue with Vuetify's CRUD Datatable UI Component in a page named "Category". The problem arises when trying ...

Automatically expand all PrimeNG Accordion panels for easy printing purposes

I've implemented the PrimeNG library's accordion component in my angular project. You can find more information here. In my template, I have some custom css styling for printing the page that looks like this: @media print { .profile-progress ...

Is there a way to make my for loop search for the specific element id that I have clicked on?

When trying to display specific information from just one array, I'm facing an issue where the for loop is also iterating through other arrays and displaying their names. Is there a way to only show data from the intended array? const link = document. ...

Using TypeScript to pass an array list as a parameter in the HTTP native GET method

Attempting to send an array list parameter. The codeList parameter contains an array like this: [ { "projCode": "11-1115", "cblTagNo": "571_GE001-RC1" }, { "projCode": "11-1115", "cblTagNo": "571_GE001-S" } ] Encountering the erro ...

Proper method for transmitting error data, yet program execution persists

How should I properly transmit error details to my backend? I have a specific scenario in mind. While the code is executing, an error occurs due to a faulty value. In such cases, I aim to capture and send error information to the backend without halting t ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

Angular 17: Issue with _HttpClient Provider Not Found in Standalone Component Utilizing ApiService

I have been developing a cutting-edge Angular 17 application that integrates the Spotify API using the innovative standalone component functionality. However, I am facing an issue while attempting to inject the HttpClient into a service. Despite meticulous ...

How to Invoke onRightButtonPress Function Within NavigatorIOS Component in React Native

In my react-native NavigatorIOS app, I am trying to use the onRightButton feature. I want to call a function from the component I am pushing, but I can't figure out how to do it. Here's an example of my code: this.props.navigator.push({ compon ...

A static factory method within an abstract class

I am currently developing a class system using Typescript. The main structure consists of an abstract class called Component, which includes a static method called create(). This method is utilized on child classes to generate specific instances. abstract ...

Is there a way to pass an object as a parameter when calling a function in JavaScript?

Is it possible to pass an object as a parameter to a function that is a value of another object? I know how to pass a string easily and even a variable as a string. But passing an object seems to be tricky. Let's consider the following 2 objects: var ...