plastikaweb
9/24/2019 - 3:06 PM

Typescript decorators

export function sealed(name: string) {
  return function (target: Function): void {
    console.log(`Sealing the constructor ${name}`);
    Object.seal(target);
    Object.seal(target.prototype);
  }
}

export function logger<TFunction extends Function>(target: TFunction): TFunction {
  let newConstructor: Function = function() {
    console.log(`Creating new instance.`);
    console.log(target);
  }
  newConstructor.prototype = Object.create(target.prototype);
  newConstructor.prototype.constructor = target;
  return <TFunction>newConstructor;
}
import { sealed, logger } from './decorators';

@sealed('Librarian')
@logger
export class Librarian {
  name: string;
  email: string;
  department: string;
}

@logger
export class NewLibrarian {
  name: string;
  email: string;
  department: string;
}

let lib1 = new Librarian();
let lib2 = new NewLibrarian();
// Sealing the constructor function Librarian() {}
// Creating new instance.
// ƒ Librarian()
// Creating new instance.
// ƒ NewLibrarian()