Decorators


Decorators provide a way to add annotations and modify classes and class members at design time. They are a special kind of declaration that can be attached to class declarations, methods, accessors, properties, or parameters.

function readonly(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.writable = false;
}

class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    @readonly
    greet() {
        return "Hello, " + this.greeting;
    }
}

Exercise

Write a decorator called log that logs to the console each time a method is called. Apply this decorator to a method within a class.


Copyright © learn-ts.org. Read our Terms of Use and Privacy Policy