Skip to content
TypeScript

Decorators

Class and method decorators.

By EZ4Code Team
decoratordecorator

Code

function log(target: any, key: string, desc: PropertyDescriptor) {
  const original = desc.value;
  desc.value = function (...args: any[]) {
    console.log(`Call ${key}(${args})`);
    return original.apply(this, args);
  };
}

function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Service {
  @log
  greet(name: string) {
    return `Hello ${name}`;
  }
}

Explanation

Decorators modify classes and behavior; requires enabling experimentalDecorators.

More TypeScript Snippets