Enhancing Typescript decorators by adding extra arguments to the constructor

After reviewing the typescript decorators documentation, it is noted that the example for replacing a constructor does not involve passing any arguments to the decorator function. How can I achieve this differently?

This is the relevant snippet from the documentation:

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
  return class extends constructor {
    newProperty = "new property";
    hello = "override";
  }
}

@classDecorator
class Greeter {
  property = "property";
  hello: string;
  constructor(m: string) {
    this.hello = m;
  }
}

Now, I wish to pass arguments by utilizing the decorator as shown below:

@classDecorator({
  // some object properties fitting DecoratorData type
})

My attempt at adding a second data parameter looked like this:

function classDecorator<T extends {new(...args:any[]):{}}>(constructor: T, data: DecoratorData)

However, this resulted in a "2 arguments required, got 1" tslint error. Even inserting a null placeholder did not solve the issue. I also experimented with using the constructor parameter as a second optional parameter, but this led to a signature mismatch error.

Answer №1

To enhance your code, consider implementing a decorator generator. This type of function can be designed to return a decorator function, allowing for additional customization. The generator function has the ability to accept extra arguments, which can then be captured and utilized within the inner decorator function.

function customDecorator(data: DecoratorData) {
    return function <T extends { new(...args: any[]): {} }>(constructor: T) {
        return class extends constructor {
            newProperty = "new property";
            hello = "override";
            // utilize data here 
        }
    }
}

@customDecorator({ data: "" })
class Greeter {
    property = "property";
    hello: string;
    constructor(m: string) {
        this.hello = m;
    }
}

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

Using Typescript and Next.js to handle error messages returned from Axios responses

My Next.js application makes an API call to validate a registration form. The server returns error messages in the following format: {"message":"The given data was invalid.","errors":{"email":["The email has alr ...

How to correctly type the return value of an asynchronous thunk in Redux Toolkit using TypeScript

I am currently working with an async thunk that looks like this: export const updateIndexingConfig = createAsyncThunk( "settings/updateIndexingConfig", (config: UpdateIndexingConfigurationRequest) => { return sdkClient.updateIndexingCo ...

A guide on converting array values to objects in AngularJS HTML

Here is my collection of objects: MyCart = { cartID: "cart101", listProducts : [ {pid:101, pname:"apple", price: 200, qty:3}, {pid:102, pname:"banana", price: 100, qty:12} ] } I have incorporated a form in ...

Script for running a React app with Prettier and eslint in a looping fashion

My Create React App seems to be stuck in a compile loop, constantly repeating the process. Not only is this behavior unwanted, but it's also quite distracting. The constant compiling occurs when running the default npm run start command. I suspect t ...

Access Azure-Active Directory through cypress tests

Currently, I'm faced with the task of creating automated tests for an application that requires login to Azure Active Directory. These tests are being written using Cypress and TypeScript. In search of a solution, I am seeking advice on how to execute ...

Error in nodejs typescript multer S3 upload - Cannot read map properties of undefined

I've created a route to upload files to an S3 bucket, and it's working perfectly. However, when I try to integrate it into my Accommodation controller with additional logic, I'm getting the error Cannot read properties of undefined (reading ...

How can we stop the parent modal from closing if the child component is not valid?

I have a main component with a modal component that takes another component as a parameter. The child modal component has some logic where I need to check if the child component is valid before closing the modal. const MainComponent: FC<IProps> => ...

Implementing Angular 2 - Steps to ensure a service is accessible within the app module

I'm running into an issue trying to utilize a function within a service that I believed was globally accessible. The service in question is named SavedNotificationService: import { Injectable } from '@angular/core'; @Injectable() export cl ...

The significance of zone.js and rxjs within the context of Angular 2

As a newcomer to Angular2, I recently learned about zone.js and rxjs. I'm curious to know if they both serve the same purpose for handling asynchronous tasks, or if each has its own specific role. Can someone explain to me the exact reasons why zone.j ...

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

Using TypeScript with React: Automatically infer the prop type from a generic parameter

I've developed a component that retrieves data from an API and presents it in a table. There's a prop that enables the fetched value to be displayed differently within the table. Here's how I currently have the prop types set up: // T repres ...

Custom hooks for Typescript and Javascript

As a beginner, I am currently working on refactoring JavaScript hooks into TypeScript. However, I am facing an issue where I cannot get the button onClick event to change state. Can anyone provide assistance with this? Here is the useToggler component: i ...

How to make an optional prop with a default value non-nullable in a ts+react component?

Is there a way to modify a React component to accept an optional prop and then treat it as non-null within the component itself? For example, consider the following basic component: import React from 'react'; type props = { x?: number; }; c ...

What is the best way to connect a toArray function to an interface property?

Consider the following scenario: interface D { bar: string } interface B { C: Record<string, D> // ... additional properties here } const example: B = { C: { greeting: { bar: "hi" } } // ... additional properties here } Now I would like t ...

Beware of potential issues with FontAwesomeIcon when incorporating it into a Typescript file

I'm currently working with NextJS and Typescript. I encountered an issue when trying to import FontAwesomeIcon like this <FontAwesomeIcon icon={faCheck as any} /> as it triggered a warning in the console stating "Warning: FontAwesomeIcon: Suppor ...

Is there a beginner's pack or trial version available for utilizing TypeScript with IBM Cloud Functions / OpenWhisk?

While working on developing actions in IBM Cloud Functions, I have been primarily using Node.js / Javascript and Python for coding. However, I haven't come across specific instructions on how to incorporate TypeScript into IBM Cloud Functions. I am c ...

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

Apply rounded corners to the table row

Currently, I am utilizing a datagrid to display information. I have been attempting to implement border radius on all the table rows, but it doesn't seem to be working. Does anyone have insight into how I can apply border-radius to all rows in the t ...