Tips for using a TypeScript method decorator while maintaining the expected `this` scope

It was brought to my attention that the issue I encountered was due to the use of GraphQL resolvers in running my decorated method. This resulted in the scope of this being undefined. Nevertheless, the core of the question provides valuable insights for anyone facing challenges with decorators.


Here is a simplified version of the decorator I intend to use:

const someDecorator = (argPassed: any) => {

  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {

    const originalMethod = descriptor.value;

    // Perform operations here...
    console.log(argPassed);

    // Wrapping the original method
    descriptor.value = (...args: any[]) => {

      const result = originalMethod.apply(this, args);

      return result;
    };
  };
};

I've utilized arrow functions within the decorator as it was necessary to ensure a certain scope is maintained, albeit different from a typical this scope.

Below is an example of the class where I'm utilizing the decorator on a specific method:

class SomeClass {

  constructor() {
  }

  @someDecorator('Passing this in...')
  public doingSomething(argPassed: string) {

    console.log(this); // Outputs: { default: SomeClass { otherMethodInMyClass: [Function] } }

    //  Unfortunately, I can't do this
    //  this.otherMethodInMyClass is not a function
    this.otherMethodInMyClass(argPassed);

  }

  private otherMethodInMyClass = (argPassed: any) => {
    // Implement functionality...
  }

}

Currently, when using the decorator, the scope returned by doingSomething is:

{ default: SomeClass { otherMethodInMyClass: [Function] } }

In contrast, without the decorator, I get:

SomeClass { doingSomething: [Function], otherMethodInMyClass: [Function] }

Is this expected behavior? If not, what might be going wrong? If it is normal, how can I enable my method to utilize its own scope since I need to call other methods thereafter?

Update: As correctly pointed out by @jcalz, an arrow function does not have its own this context. However, when I employed a non-arrow function throughout the decorator, this ended up being undefined.

Thank you in advance

Answer №1

It appears that the issue in your query arises from using an arrow function as a method, which is not recommended due to arrow functions lacking their own this context.

You mentioned that altering this didn't resolve your problem, but I am unable to replicate it:

const someDecorator = (argPassed: any) => {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        const originalMethod = descriptor.value;
        console.log("ARGPASSED: ");
        console.log(argPassed);
        // anonymous function, not arrow
        descriptor.value = function (...args: any[]) {
            const result = originalMethod.apply(this, args);
            return result;
        };
    };
};

class SomeClass {    
    constructor() { }

    @someDecorator('Passing this in...')
    public doingSomething(argPassed: string) {   
        console.log("THIS: ")
        console.log(this); 
        this.otherMethodInMyClass(argPassed);
    }

    private otherMethodInMyClass = (argPassed: any) => { }
}

new SomeClass().doingSomething("abc");
// ARGPASSED: 
// Passing this in...
// THIS: 
// Object { otherMethodInMyClass: otherMethodInMyClass() }

Link to code in Playground

Based on my examination, everything seems to be functioning correctly. If you are still facing issues, please provide more information about your setup in your inquiry. It is always beneficial to ensure that the code you include in your questions forms a reproducible example. Best of luck!

Answer №2

Encountering a similar challenge while integrating class methods as GraphQL resolvers, I found a workaround by transforming the class into a singleton. By doing so, I could access private methods from the singleton instance rather than directly within this.

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

Attempting to utilize Array Methods with an Array Union Type

Currently, I am in the process of refactoring an Angular application to enable strict typing. One issue I have encountered is using array methods with an array union type in our LookupService. When attempting to call const lookup = lookupConfig.find(l =&g ...

Is there a technique to block small increments in a Time Input field?

Currently in the process of developing a tool to automate task scheduling within an Angular app. I am looking for a way to restrict the user's input when selecting the hour for task execution without having to install a complex input management packag ...

Error: The class constructor [] must be called with the 'new' keyword when creating instances in a Vite project

I encountered an issue in my small Vue 3 project set up with Vite where I received the error message Class constructor XX cannot be invoked without 'new'. After researching online, it seems that this problem typically arises when a transpiled cla ...

Tips for utilizing the material ui auto-complete search feature

I am in search of an alternative to material-ui-search-bar because it is no longer being maintained. I have been suggested to try using Material UI's auto complete instead. However, from the examples I've seen, it seems like only text field struc ...

Guide to leveraging tanstack table v8 for sorting data within a specific date range

Received data from API: const abc = [ { date: '2023-12-8', value: 'mop' },{ date: '2023-10-8', value: 'qrs' } ] How can we create a date range using two input fields when the dates are in string forma ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

Encountering a SonarQube error message stating "Unnecessary 'undefined' should be removed" when using "undefined" as a function argument

When calling a function, I have been passing "undefined" multiple times as a parameter. However, the SonarQube report is flagging an error stating "Remove this redundant undefined". https://i.stack.imgur.com/YhOZW.png It should be noted that the function ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

The Tools of the Trade: TypeScript Tooling

Trying out the amazing Breeze Typescript Entity Generator tool but encountering an error consistently. Error: Experiencing difficulty in locating the default implementation of the 'modelLibrary' interface. Options include 'ko', 'b ...

Filtering an array in Angular based on two specific property values

I am facing a challenge with deleting items from an array based on two property values. If we were to compare it to the classic Sql delete command, the equivalent would look something like this: DELETE oImages WHERE idOffertRow = 1 and idProductImage = 2 ...

Troubles with Katex/ngx-markdown Display in Angular 16

In my Angular 16 application, I utilize the ngx-markdown library alongside Katex and other dependencies. A challenging situation arises when the backend (an LLM) responds with markdown text that conflicts with Katex delimiters during rendering. I attempte ...

The error message "The export named 'render' (which was imported as 'render') could not be found" appeared

Encountering an error when building a Vue project with TypeScript and Webpack, specifically the "export 'render' (imported as 'render') was not found" issue. Below is the full error code: export 'render' (imported as 'ren ...

Modify the "field" key type within the GridColDef interface of MUI DataGrid

Is there a way to assign an array of specific strings to the default type of GridColDef's field key, which is typically set to string? I attempted solutions like Array<Omit<GridColDef, 'field'> & {field: 'name' | &apo ...

The function signature '() => Element' is incompatible with the type 'string'

Greetings! I have a standard function that returns a span with a prop (if I'm not mistaken). In my TS code, I am encountering this error: Error image Below is the code from the file named qCard.tsx: import { QuestionAnswerTwoTone } from "@material- ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

Using TypeScript to efficiently filter an Array by converting all values to lowercase

I have a custom array in TypeScript that needs to be filtered based on the city and job, with case-insensitivity as a requirement. array = [{ name: "Hardik", city: null, job: null }, { name: "John", city: "Ahmedabad", job: "IT" }, { name: "Margie", c ...

Is there another option for addressing this issue - A function that does not declare a type of 'void' or 'any' must have a return value?

When using Observable to retrieve data from Http endpoints, I encountered an error message stating that "A function whose declared type is neither 'void' nor 'any' must return a value." The issue arises when I add a return statement in ...

Incorporate a vibrant red circle within a tab of the navigation bar

I'm looking to incorporate a red dot with a number into a messaging tab to indicate new messages. Below is the HTML code: <ul class="nav pw-nav pw-nav--horizontal"> <li class="nav-item"> <a class="nav ...