TypeScript Code Weaving

Is there a way to do code weaving in TypeScript?

What I'm trying to do is insert a piece of code as the first line of each function in my TypeScript application, and I won’t do it manually (this manual approach is tedious and error prone).

+4
source share
1 answer

While compilation is incorrect at compile time, for class methods, you can use method decorators to wrap these methods with additional functions at run time. Consider this decorator example, which forces invocation to also write received arguments to the console:

// 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;

, :

  • ,

, .

+4

Source: https://habr.com/ru/post/1628271/


All Articles