【问题标题】:TypeScript code weavingTypeScript 代码编织
【发布时间】:2016-05-21 23:16:47
【问题描述】:

有没有办法在 TypeScript 中进行代码编织?

我要做的是在我的 TypeScript 应用程序中的每个函数的第一行注入一段代码,我不会手动执行此操作(这种手动方法很乏味且容易出错)。

【问题讨论】:

    标签: typescript compile-time-weaving


    【解决方案1】:

    虽然不是真正的编译-time weaving,但您只能使用method decorators运行时 使用附加功能包装这些方法。考虑这个示例方法装饰器,它使调用还将接收到的参数记录到控制台中:

    // the method decorator function
    function log(target: Object, key: string, descriptor: any) {
        // replace original property descriptor of method with the following one:
        return {
            // the new method:
            value: function (...args: any[]) {
                // log arguments
                console.log(args);
    
                // invoke the original method as part of the new method,
                // and return its returned value (if any)
                return descriptor.value.apply(this, args);
            }
        };
    }
    

    将这个装饰器应用到一个方法上很简单:

    class Calculator {
        @log
        add(a: number, b: number) {
            return a + b;
        }
    }
    

    快速解释:Typescript 中的方法装饰器具有以下签名:

    <T>(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor<T>) => PropertyDescriptor<T> | void;
    

    换句话说,方法装饰器接受 3 个参数:

    1. 定义原始方法的原型对象
    2. 方法的属性键
    3. 方法的属性描述符

    方法装饰器返回单个属性描述符,它是类型上原始方法的替换。

    【讨论】:

    • 我正在阅读exact same thing :) 我认为装饰器适合这个问题,但我仍然需要手动装饰每个方法,有没有办法避免这种情况?我可以“隐式”装饰每个方法吗?
    • @Gigtsu 您可以使用class decorator 来装饰一个类型的所有方法(通过迭代原型的自己的属性并查看它们是否是函数),但我不知道自动添加方法的方法整个代码库中每一个方法的装饰器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2011-11-03
    • 2014-10-01
    相关资源
    最近更新 更多