简体   繁体   English

你能使用超级 class 方法作为装饰器方法吗 - Typescript

[英]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:然后是装饰器 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:但是,我不想为装饰器定义单独的 function,而是希望装饰器 function 来自超级 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.目前,关键字“this”有一个编译错误,表明它可能未定义。 I've run this code and it doesn't execute the decorator function.我已经运行了这段代码,它没有执行装饰器 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!先感谢您!

No, you can't do that, the decorator is applied when the class is defined not when it's instantiated.不,你不能这样做,当 class 被定义而不是在实例化时应用装饰器。 There are no instance methods from your superclass available.您的超类中没有可用的实例方法。

However, you can do this with a static method of course:但是,您当然可以使用static方法执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM