When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase:

function Decorator(SampleClass: Sample) {
  console.log('Inside the decorator function');

  return function (args) {
    console.log('Inside the high order function of the decorator: ', args);
    let sample = new SampleClass();
  }
}

@Decorator
class Sample {

  a = 1;
  static b = 2;

  constructor(args) {
    console.log('Inside the constructor of Sample')
    console.log('Instance values of Sample: ', this.a);
    console.log('Static value of Sample: ', Sample.b);
  }
}

new Sample(123);

After compiling and running the code, it displays:

Inside the decorator function
Inside the high order function of the decorator:  123
Inside the constructor of Sample
Instance values of Sample:  1
Static value of Sample:  undefined

I have noticed that I can access the static value b in the high order function using SampleClass.b. However, accessing it within an instance of Sample seems to be challenging.

Answer №1

When utilizing decorators, the key concept to grasp is that by returning a value from the decorator, you essentially replace the decorated class entirely. This means that although you can successfully implement a new Foo using the returned function, it won't inherit any properties from the original Foo, rendering them unavailable on the replaced version.

To resolve this issue, one straightforward solution is to create and return an anonymous class that inherits from the class supplied to the decorator.

function Bar(FooClass: typeof Foo) {
    console.log('inside Bar decorator');
    return class extends FooClass {
        constructor(args: any) {
            super(args);
            console.log('within Bar higher-order function: ', args);
        }
    };
}

@Bar
class Foo {

    a = 1;
    static b = 2;
    constructor(args: any) {
        console.log('within Foo constructor')
        console.log('Instance of Foo with a: ', this.a);
        console.log('Static property b of Foo: ', Foo.b);
    }
}

new Foo(123);

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

What is the best way to retrieve HTML content using an Angular method?

Okay, so the title might not be the greatest...but I couldn't think of anything better: I want to emphasize search keywords in the result list...that's why I'm having trouble with this problem. CSS: .highlightText{ font-weight: bold; } In ...

Tips for testing nested subscribe methods in Angular unit testing

FunctionToTest() { this.someService.method1().subscribe((response) => { if (response.Success) { this.someService.method2().subscribe((res) => { this.anotherService.method3(); }) } }); } Consider the following scenario. ...

Tips for utilizing Variant on an overridden component using as props in ChakraUI

I created a custom Component that can be re-rendered as another component using the BoxProps: export function Label ({ children, ...boxProps }: BoxProps) { return ( <Box {...boxProps}> {children} </Box> ); } It functio ...

Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet: import * as appSettings from 'application-settings'; try { // shim the 'localStorage' API with application settings module global.localStorage = { ...

Setting up Tarui app to access configuration data

I am looking to save a Tauri app's user configuration in an external file. The TypeScript front end accomplishes this by: import {appConfigDir} from "tauri-apps/api/path"; ... await fetch(`${await appConfigDir()}symbol-sets.json`) { ... ...

Material-UI chart displays only loading lines upon hovering

Currently, I am utilizing a Material UI Line chart in my NextJS 14 application to showcase some data. Although the data is being displayed properly, I have encountered an issue where the lines on the chart only render when hovered over, rather than appeari ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

Is it necessary to manually unsubscribe from observables in the main Angular component?

I'm facing a dilemma with my Observable in the root Angular (6.x) component, AppComponent. Typically, I would unsubscribe from any open Subscription when calling destroy() using the lifecycle hook, ngOnDestroy. However, since the AppComponent serv ...

Problem with extending a legacy JavaScript library using TypeScript

Can someone assist me with importing files? I am currently utilizing @types/leaflet which defines a specific type. export namespace Icon { interface DefaultIconOptions extends BaseIconOptions { imagePath?: string; } class Default exte ...

Missing from the TypeScript compilation are Angular5's polyfills.ts and main.ts files

Here is the structure of my Angular5 project. https://i.stack.imgur.com/tmbE7.png Within both tsconfig.app.json and package.json, there is a common section: "include": [ "/src/main.ts", "/src/polyfills.ts" ] Despite trying various solu ...

The Angular Button fails to display when all input conditions are met

I'm currently working on validating a form using this link. The requirement is simple - when an input field is invalid, the `save` button should be disabled. Conversely, when all input fields are valid, the `SAVE` button should be enabled/shown. The & ...

No matter which port I try to use, I always receive the error message "listen EADDRINUSE: address already in use :::1000"

Encountered an error: EADDRINUSE - address already in use at port 1000. The issue is within the Server setupListenHandle and listenInCluster functions in the node.js file. I am currently running this on a Mac operating system, specifically Sonoma. Despit ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Converting axios response containing an array of arrays into a TypeScript interface

When working with an API, I encountered a response in the following format: [ [ 1636765200000, 254.46, 248.07, 254.78, 248.05, 2074.9316693 ], [ 1636761600000, 251.14, 254.29, 255.73, 251.14, 5965.53873045 ], [ 1636758000000, 251.25, 251.15, 252.97, ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

A guide to effectively utilizing a TypeScript cast in JSX/TSX components

When trying to cast TypeScript in a .tsx file, the compiler automatically interprets it as JSX. For example: (<HtmlInputElement> event.target).value You will receive an error message stating that: JSX element type 'HtmlInputElement' is ...

Exploring .ENV Variables using Angular 2 Typescript and NodeJS

After completing the Angular2 Quickstart and tutorials, I'm now venturing into connecting to a live REST Api. I need to include authentication parameters in my Api call, and from what I've gathered, it's best practice to store these paramete ...

Utilizing the useRef hook in React to retrieve elements for seamless page transitions with react-scroll

I've been working on creating a single-page website with a customized navbar using React instead of native JavaScript, similar to the example I found in this reference. My current setup includes a NavBar.tsx and App.tsx. The NavBar.tsx file consists o ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

What is the best method for inserting a hyperlink into the JSON string obtained from a subreddit?

const allowedPosts = body.data.children.filter((post: { data: { over_18: any; }; }) => !post.data.over_18); if (!allowedPosts.length) return message.channel.send('It seems we are out of fresh memes!, Try again later.'); const randomInd ...