Javascript
Decorators

Decorators

A decorator is basically a function that add some super power to existing method or class (like a higher order function you have on react). Is called a meta programming as it modified the existing function or completely replace how the function works.

Below is the type of decorator in typescript

 
type Decorator = (value: Input, context: {
    kind: string, // kind is method or class
    name: string | symbol,
    access: {
        get?(): unknown,
        set?(value: unknown): void; 
    },
    private: boolean;
    static: boolean;
    addIntializer?(initializer:() => void): void
}) => Output | void

value: Input here is the function or a class itself. For eg: below class getAge method is the input. Output can be whatever we want.

Decorator Example

 
export const log = (value, {kind, name}) => {
    if (kind === "method") {
        return function(...args) {
            try {
                const result = value.apply(this, args);
                return "some additional thing in result" + result;
            } catch (error) {
                throw error
            }
        }
    } else if (kind === "class") {
        return class extends value {
            constructor (...args) {
                super(...args)
                this.age = args[1] + 10 // modifying the class's property
            }
        }
    }
}
 
 
 
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
 
    @log
    getAge(){
 
    }
}