Shawn Peery
Shawn Peery

Reputation: 45

Can you use super class methods as decorator methods - Typescript

This is something that if I'm able to achieve will be able to design a very easily extendible decorator factory for a project I'm working on.

Basically, I want to be able to use a super class's methods as a decorator for the sub-classes property.

This is usually how decorators work:

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

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

export default Main

And then the decorator function:

const propertyNames = [];

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

However, instead of defining a separate function for the decorator, I'd like the decorator function to come from the super class:

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;

Currently the keyword "this" has a compilation error that states it's possibly undefined. I've run this code and it doesn't execute the decorator function.

My question is this approach possible with some type of workaround? If this is possible that will significantly improve my organization.

Thank you in advance!

Upvotes: 0

Views: 396

Answers (1)

Bergi
Bergi

Reputation: 664297

No, you can't do that, the decorator is applied when the class is defined not when it's instantiated. There are no instance methods from your superclass available.

However, you can do this with a static method of course:

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

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

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

export default Main

Upvotes: 2

Related Questions