plastikaweb
9/24/2019 - 3:38 PM

Method decorators

export function writable(isWritable: boolean) {
  return function (target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log(`Setting ${propertyKey}.`);
    descriptor.writable = isWritable;
  }
}
import  { writable } from './decorators';

export class Employee {
  title: string;

  @writable(true)
  add(): void {
    console.log('Employee added.');
  }

  @writable(false)
  log(): void {
    console.log(`Employee has the title ${this.title}.`);
  }
}

const employee = new Employee();

try {
  employee.add = () => console.log('changed add.');
  employee.log = () => console.log('changed log.');
} catch (error) {
  console.log(error.message);
}

employee.add();
employee.log();

// Setting add.
// Setting log.
// "log" is read-only
// changed add.
//Employee has the title undefined.