JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Method and Property Decorators

19 min read ยท
In this lesson12

"Oversight of individual operations in Jurassic Park is just as important as managing the entire park," explains Dr. Henry Wu, InGen's chief geneticist. "Just as we monitor every aspect of dinosaur life - their feeding, behavior, and growth - we must also control and secure individual operations in our system."

In TypeScript, after understanding class decorators, the natural next step is to delve into method and property decorators. These decorators allow us to precisely modify the behavior of specific class members, just as in Jurassic Park, where every operation, from feeding dinosaurs to securing enclosures, requires special oversight and protocols.

Introduction to method and property decorators

Method and property decorators allow modifying the behavior, access, or value of individual class members. Thanks to them, we can:

  1. Add additional behavior before or after method execution
  2. Validate method parameters
  3. Cache method results
  4. Measure method execution time
  5. Control property access
  6. Transform property values
  7. Add metadata to methods and properties

Method decorators

In experimentalDecorators mode, method decorators are functions that take three parameters:

  1. target - the class prototype (for instance methods) or the class constructor (for static methods)
  2. propertyKey - the method name
  3. descriptor - the property descriptor for the method

Standard decorators in TypeScript 5.0+ (without that option) receive two arguments instead: the method itself and a context object.

Basic method decorator syntax:

function methodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  // Modification of the method descriptor
  // Return the modified descriptor or undefined
}

class MyClass {
  @methodDecorator
  myMethod() {
    // Method implementation
  }
}

Example: Operations logging system in Jurassic Park

Let's start with a simple method decorator that will log operation execution in Jurassic Park:

// Method decorator that logs calls
function LogOperation(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  // Save the original method
  const originalMethod = descriptor.value;

  // Override the method
  descriptor.value = function(...args: any[]) {
    console.log(`[${new Date().toISOString()}] Calling ${propertyKey} with arguments: ${JSON.stringify(args)}`);

    try {
      // Call the original method
      const result = originalMethod.apply(this, args);

      // Log the result
      console.log(`[${new Date().toISOString()}] ${propertyKey} completed. Result: ${JSON.stringify(result)}`);

      return result;
    } catch (error) {
      // Log the error
      console.error(`[${new Date().toISOString()}] ${propertyKey} failed with error: ${error}`);

      // Re-throw the error
      throw error;
    }
  };

  return descriptor;
}

// Applying the decorator in the enclosure management class
class EnclosureManagement {
  constructor(private employeeName: string) {}

  @LogOperation
  openEnclosure(enclosureId: string): boolean {
    console.log(`${this.employeeName} opens enclosure: ${enclosureId}`);
    // Enclosure opening logic here
    return true;
  }

  @LogOperation
  closeEnclosure(enclosureId: string): boolean {
    console.log(`${this.employeeName} closes enclosure: ${enclosureId}`);
    // Enclosure closing logic here
    return true;
  }

  checkStatus(enclosureId: string): string {
    // This method is not logged
    return "Enclosure closed";
  }
}

// Using the class with decorated methods
const manager = new EnclosureManagement("John");
manager.openEnclosure("A-001");
manager.closeEnclosure("A-001");
manager.checkStatus("A-001"); // This operation will not be logged

In the example above, the LogOperation decorator records every method call, its arguments, and the result or error. The openEnclosure and closeEnclosure methods are logged, while the checkStatus method has no decorator, so it is not logged.

Method decorators with parameters

We can also create method decorators that accept parameters:

// Method decorator with parameters
function RequireAccessLevel(level: number) {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    // Save the original method
    const originalMethod = descriptor.value;

    // Override the method
    descriptor.value = function(...args: any[]) {
      // Check if the object has an access level property
      if (!(this as any).accessLevel) {
        throw new Error("Object does not have a defined access level!");
      }

      // Verify the access level
      if ((this as any).accessLevel < level) {
        throw new Error(`Required access level: ${level}, available: ${(this as any).accessLevel}`);
      }

      // Call the original method
      return originalMethod.apply(this, args);
    };

    return descriptor;
  };
}

// Class representing a laboratory
class GeneticLaboratory {
  constructor(public employeeName: string, public accessLevel: number) {}

  @RequireAccessLevel(1)
  readDnaData(dinosaurId: string): string {
    return `Dinosaur DNA ${dinosaurId}: ACGT...`;
  }

  @RequireAccessLevel(2)
  modifyDNA(dinosaurId: string, sequence: string): boolean {
    console.log(`DNA modification of dinosaur ${dinosaurId}: ${sequence}`);
    return true;
  }

  @RequireAccessLevel(3)
  createNewSpecies(name: string, baseDNA: string): string {
    const newSpeciesId = `NGT-${Math.floor(Math.random() * 1000)}`;
    console.log(`Creating new species: ${name} (ID: ${newSpeciesId})`);
    return newSpeciesId;
  }
}

// Using the class with different access levels
const intern = new GeneticLaboratory("Tim", 1);
const scientist = new GeneticLaboratory("Dr. Grant", 2);
const director = new GeneticLaboratory("Dr. Wu", 3);

// Testing access
try {
  console.log(intern.readDnaData("D-001")); // Will work
  intern.modifyDNA("D-001", "ACGT");         // Will throw error
} catch (error) {
  console.error(error.message);
}

try {
  scientist.modifyDNA("D-001", "ACGT");        // Will work
  scientist.createNewSpecies("Neo-Raptor", "ACGT..."); // Will throw error
} catch (error) {
  console.error(error.message);
}

// Director has full access
director.createNewSpecies("Indominus Rex", "ACGT...");

In this example, the RequireAccessLevel decorator checks whether the person calling the method has a sufficient access level. Different methods require different access levels, reflecting real security protocols that could exist in Jurassic Park.

Property decorators

Property decorators are similar to method decorators but receive only two parameters:

  1. target - the class prototype (for instance properties) or the class constructor (for static properties)
  2. propertyKey - the property name

Basic property decorator syntax:

function propertyDecorator(target: any, propertyKey: string) {
  // Decorator implementation
}

class MyClass {
  @propertyDecorator
  myProperty: string;
}

Since property decorators don't receive a descriptor, they are often used to generate getters and setters or to apply metadata.

Example: Resource monitoring system in Jurassic Park

Let's implement a property decorator that will monitor resource changes in Jurassic Park:

// Property decorator that monitors changes
function MonitorChanges(target: any, propertyKey: string) {
  // Create a unique name for the private property
  const privateName = Symbol(propertyKey);

  // Define getter and setter
  Object.defineProperty(target, propertyKey, {
    get: function() {
      // Return the private property value
      return this[privateName];
    },
    set: function(value: any) {
      // Save the old value
      const oldValue = this[privateName];

      // Log the change if it's not the first assignment
      if (this[privateName] !== undefined) {
        console.log(`[CHANGE][${this.constructor.name}] ${propertyKey}: ${oldValue} -> ${value}`);
      }

      // Save the new value
      this[privateName] = value;
    },
    enumerable: true,
    configurable: true
  });
}

// Class monitoring park resources
class ParkResources {
  @MonitorChanges
  foodAmount: number = 1000;

  @MonitorChanges
  generatorsState: "Active" | "Backup" | "Disabled" = "Active";

  @MonitorChanges
  gateStatus: "Open" | "Closed" = "Closed";

  constructor(public sectionName: string) {}

  useFood(amount: number): boolean {
    if (this.foodAmount >= amount) {
      this.foodAmount -= amount;
      return true;
    }
    return false;
  }

  refillFood(amount: number): void {
    this.foodAmount += amount;
  }

  toggleGenerators(state: "Active" | "Backup" | "Disabled"): void {
    this.generatorsState = state;
  }

  toggleGate(status: "Open" | "Closed"): void {
    this.gateStatus = status;
  }
}

// Using the class with monitored properties
const sectionA = new ParkResources("Section A");

// Testing property changes
sectionA.useFood(200);  // foodAmount: 1000 -> 800
sectionA.refillFood(500);  // foodAmount: 800 -> 1300
sectionA.toggleGenerators("Backup");  // generatorsState: Active -> Backup
sectionA.toggleGate("Open");  // gateStatus: Closed -> Open

In this example, the MonitorChanges decorator creates a getter and setter for properties that log every value change. This way, we can track when and what changes were made, which is crucial for monitoring park resources.

Combining method and property decorators

We can combine different method and property decorators to create more advanced behaviors:

// Decorator measuring method execution time
function MeasureExecutionTime(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function(...args: any[]) {
    const start = performance.now();
    const result = originalMethod.apply(this, args);
    const end = performance.now();

    console.log(`[TIME] ${propertyKey}: ${(end - start).toFixed(2)}ms`);

    return result;
  };

  return descriptor;
}

// Decorator validating method parameters
function ValidateParameters(validator: (args: any[]) => boolean, errorMessage: string) {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function(...args: any[]) {
      if (!validator(args)) {
        throw new Error(`[VALIDATION ERROR] ${propertyKey}: ${errorMessage}`);
      }

      return originalMethod.apply(this, args);
    };

    return descriptor;
  };
}

// Decorator caching method results
function Cache(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  const cache = new Map<string, any>();

  descriptor.value = function(...args: any[]) {
    const key = JSON.stringify(args);

    if (cache.has(key)) {
      console.log(`[CACHE] ${propertyKey}: Used cached result for ${key}`);
      return cache.get(key);
    }

    const result = originalMethod.apply(this, args);
    cache.set(key, result);

    return result;
  };

  return descriptor;
}

// Decorator adding a value range for a numeric property
function Range(min: number, max: number) {
  return function(target: any, propertyKey: string) {
    // Create a unique name for the private property
    const privateName = Symbol(propertyKey);

    // Define getter and setter
    Object.defineProperty(target, propertyKey, {
      get: function() {
        return this[privateName];
      },
      set: function(value: number) {
        if (value < min) {
          console.warn(`[RANGE] ${propertyKey}: Value ${value} below minimum ${min}. Setting ${min}.`);
          this[privateName] = min;
        } else if (value > max) {
          console.warn(`[RANGE] ${propertyKey}: Value ${value} above maximum ${max}. Setting ${max}.`);
          this[privateName] = max;
        } else {
          this[privateName] = value;
        }
      },
      enumerable: true,
      configurable: true
    });
  };
}

// Class managing the electric fence system
class ElectricFenceSystem {
  @Range(0, 10000)
  voltage: number = 5000; // in volts

  @Range(0, 100)
  range: number = 50; // in meters

  private statusActive: boolean = false;

  @LogOperation
  @MeasureExecutionTime
  @ValidateParameters(
    args => args[0] >= 0 && args[0] <= 10000,
    "Invalid voltage. Allowed range: 0-10000V"
  )
  setVoltage(newVoltage: number): boolean {
    // Simulating a long operation for testing the MeasureExecutionTime decorator
    for (let i = 0; i < 1000000; i++) {
      // CPU load
    }

    this.voltage = newVoltage;
    return true;
  }

  @LogOperation
  @Cache
  getSystemStatus(sectionId: string): { active: boolean; voltage: number; range: number } {
    console.log(`Fetching system status for section ${sectionId}...`);

    // Simulating a long operation
    for (let i = 0; i < 500000; i++) {
      // CPU load
    }

    return {
      active: this.statusActive,
      voltage: this.voltage,
      range: this.range
    };
  }

  @LogOperation
  @MeasureExecutionTime
  activateSystem(): boolean {
    if (this.statusActive) {
      console.log("System already active");
      return false;
    }

    console.log(`Activating electric fence system. Voltage: ${this.voltage}V, Range: ${this.range}m`);
    this.statusActive = true;

    return true;
  }

  @LogOperation
  @MeasureExecutionTime
  deactivateSystem(): boolean {
    if (!this.statusActive) {
      console.log("System already inactive");
      return false;
    }

    console.log("Deactivating electric fence system");
    this.statusActive = false;

    return true;
  }
}

// Using the class with multiple decorators
const fenceSystem = new ElectricFenceSystem();

// Testing various functionalities
fenceSystem.setVoltage(7500);  // Logs operation, measures time, validates parameter
fenceSystem.setVoltage(12000); // Will exceed range, will be set to 10000
fenceSystem.activateSystem();      // Logs operation, measures time

// Testing caching
console.log(fenceSystem.getSystemStatus("A1")); // Full operation
console.log(fenceSystem.getSystemStatus("A1")); // Uses cache
console.log(fenceSystem.getSystemStatus("B2")); // Full operation
console.log(fenceSystem.getSystemStatus("B2")); // Uses cache

// Deactivating the system
fenceSystem.deactivateSystem();

In this example, we use multiple decorators to create an advanced electric fence system:

  1. @Range - ensures property values stay within the specified range
  2. @LogOperation - logs method calls
  3. @MeasureExecutionTime - measures method execution time
  4. @ValidateParameters - checks method parameter validity
  5. @Cache - caches method results in memory

Metadata and reflection with decorators

TypeScript also allows using metadata with decorators, enabling more advanced use cases. This requires enabling the emitDecoratorMetadata and experimentalDecorators options in the tsconfig.json file and installing the reflect-metadata package.

Here is an example of using metadata with decorators:

// We need to import reflect-metadata at the start of the application
import "reflect-metadata";

// Keys for metadata
const PARAMETER_KEY = Symbol("parameters");

// Parameter decorator
function Parameter(target: any, propertyKey: string, parameterIndex: number) {
  // Get existing metadata or create empty
  const parameters: number[] = Reflect.getOwnMetadata(PARAMETER_KEY, target, propertyKey) || [];

  // Add parameter index to the list
  parameters.push(parameterIndex);

  // Save metadata
  Reflect.defineMetadata(PARAMETER_KEY, parameters, target, propertyKey);
}

// Method decorator validating parameters
function ValidateData(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function(...args: any[]) {
    // Get parameter types (requires emitDecoratorMetadata option)
    const typy = Reflect.getMetadata("design:paramtypes", target, propertyKey);

    // Get parameter indices marked with the @Parameter decorator
    const markedParameters: number[] = Reflect.getOwnMetadata(PARAMETER_KEY, target, propertyKey) || [];

    // Validate parameters
    for (const index of markedParameters) {
      const value = args[index];
      const type = typy[index];

      // Type validation
      if (value === null || value === undefined) {
        throw new Error(`Parameter #${index} of method ${propertyKey} cannot be null or undefined`);
      }

      // Validation for different types
      if (type === String && typeof value !== "string") {
        throw new Error(`Parameter #${index} of method ${propertyKey} must be a string`);
      } else if (type === Number && typeof value !== "number") {
        throw new Error(`Parameter #${index} of method ${propertyKey} must be a number`);
      } else if (type === Boolean && typeof value !== "boolean") {
        throw new Error(`Parameter #${index} of method ${propertyKey} must be a boolean`);
      } else if (type === Date && !(value instanceof Date)) {
        throw new Error(`Parameter #${index} of method ${propertyKey} must be a Date`);
      }
    }

    // Call the original method
    return originalMethod.apply(this, args);
  };

  return descriptor;
}

// Dinosaur operations class with metadata
class DinosaurOperations {
  @ValidateData
  conductResearchHealth(
    dinosaurId: string,
    @Parameter examinationDate: Date,
    @Parameter temperature: number,
    @Parameter weight: number,
    notes?: string
  ): string {
    console.log(`Health examination of dinosaur ${dinosaurId}`);
    console.log(`Date: ${examinationDate.toLocaleDateString()}`);
    console.log(`Temperature: ${temperature}ยฐC`);
    console.log(`Weight: ${weight}kg`);

    if (notes) {
      console.log(`Notes: ${notes}`);
    }

    return "Examination completed";
  }

  @ValidateData
  performVaccination(
    @Parameter dinosaurId: string,
    @Parameter vaccinationType: string,
    @Parameter vaccinationDate: Date
  ): boolean {
    console.log(`Vaccination of dinosaur ${dinosaurId}`);
    console.log(`Vaccination type: ${vaccinationType}`);
    console.log(`Date: ${vaccinationDate.toLocaleDateString()}`);

    return true;
  }
}

// Using the class with parameter validation
const operations = new DinosaurOperations();

try {
  // Correct call
  operations.conductResearchHealth(
    "D-001",
    new Date(),
    38.5,
    1200,
    "Dinosaur in good condition"
  );

  // Incorrect call - temperature is not a number
  operations.conductResearchHealth(
    "D-002",
    new Date(),
    "high" as any, // This will cause an error
    1500
  );
} catch (error) {
  console.error(error.message);
}

try {
  // Correct call
  operations.performVaccination(
    "D-003",
    "Anti-parasite vaccine",
    new Date()
  );

  // Incorrect call - date is not a Date object
  operations.performVaccination(
    "D-004",
    "Anti-flu vaccine",
    "today" as any // This will cause an error
  );
} catch (error) {
  console.error(error.message);
}

In this example, we use metadata and reflection to validate method parameters. The @Parameter decorator marks parameters that should be validated, and the @ValidateData decorator checks the types of those parameters on every method call.

Practical example: Dinosaur examination management system

Now let's combine all the discussed techniques in one larger example - a dinosaur examination management system:

// Property decorator ensuring unique IDs
function UniqueID(prefix: string = "ID") {
  return function(target: any, propertyKey: string) {
    const generateId = () => `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1000)}`;

    Object.defineProperty(target, propertyKey, {
      get: function() {
        // If the property hasn't been set yet, generate an ID
        if (!this[`_${propertyKey}`]) {
          this[`_${propertyKey}`] = generateId();
        }
        return this[`_${propertyKey}`];
      },
      set: function(value: string) {
        // Allow setting only once
        if (!this[`_${propertyKey}`]) {
          this[`_${propertyKey}`] = value;
        } else {
          console.warn(`Property ${propertyKey} has already been set and cannot be changed.`);
        }
      },
      enumerable: true,
      configurable: true
    });
  };
}

// Method decorator for date validation
function ValidateExaminationDate(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function(...args: any[]) {
    // Assume the first argument is the examination date
    const examinationDate = args[0];

    if (!(examinationDate instanceof Date)) {
      throw new Error("First parameter must be a Date instance");
    }

    const now = new Date();

    if (examinationDate > now) {
      throw new Error("Examination date cannot be in the future");
    }

    // Check if the date is not older than 30 days
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    if (examinationDate < thirtyDaysAgo) {
      console.warn("Warning: Examination date is older than 30 days");
    }

    return originalMethod.apply(this, args);
  };

  return descriptor;
}

// Method decorator for vaccination frequency control
function ControlFrequency(minDaysBetweenVaccinations: number) {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    // Map storing last vaccination dates for each dinosaur
    const lastVaccinations = new Map<string, Date>();

    const originalMethod = descriptor.value;

    descriptor.value = function(...args: any[]) {
      // Assume first argument is dinosaur ID, second is vaccination date
      const dinosaurId = args[0];
      const vaccinationDate = args[1];

      if (lastVaccinations.has(dinosaurId)) {
        const lastVaccine = lastVaccinations.get(dinosaurId)!;
        const differenceDays = Math.floor((vaccinationDate.getTime() - lastVaccine.getTime()) / (1000 * 60 * 60 * 24));

        if (differenceDays < minDaysBetweenVaccinations) {
          throw new Error(`Too early for next vaccination. Minimum interval is ${minDaysBetweenVaccinations} days. ${minDaysBetweenVaccinations - differenceDays} days remaining.`);
        }
      }

      // Save vaccination date
      lastVaccinations.set(dinosaurId, vaccinationDate);

      return originalMethod.apply(this, args);
    };

    return descriptor;
  };
}

// Examination results interface
interface ExaminationResults {
  temperature: number;  // in degrees Celsius
  weight: number;         // in kilograms
  length: number;      // in meters
  healthStatus: "Healthy" | "Light symptoms" | "Sick" | "Critical";
  notes?: string;
}

// Dinosaur examination class
class DinosaurExamination {
  @UniqueID("BAD")
  examinationId: string;

  constructor(
    public dinosaurId: string,
    public examinationDate: Date,
    public results: ExaminationResults,
    public examiner: string
  ) {}

  @LogOperation
  getReport(): string {
    return `
      === EXAMINATION REPORT ===
      Examination ID: ${this.examinationId}
      Dinosaur ID: ${this.dinosaurId}
      Date: ${this.examinationDate.toLocaleString()}
      Conducted by: ${this.examiner}

      RESULTS:
      - Temperature: ${this.results.temperature}ยฐC
      - Weight: ${this.results.weight} kg
      - Length: ${this.results.length} m
      - Health status: ${this.results.healthStatus}
      ${this.results.notes ? `- Notes: ${this.results.notes}` : ""}
    `;
  }
}

// Dinosaur vaccination class
class DinosaurVaccination {
  @UniqueID("VAC")
  vaccinationId: string;

  constructor(
    public dinosaurId: string,
    public vaccinationDate: Date,
    public genusVaccine: string,
    public dose: number,
    public vaccinator: string
  ) {}

  @LogOperation
  getReport(): string {
    return `
      === VACCINATION REPORT ===
      Vaccination ID: ${this.vaccinationId}
      Dinosaur ID: ${this.dinosaurId}
      Date: ${this.vaccinationDate.toLocaleString()}
      Vaccine type: ${this.genusVaccine}
      Dose: ${this.dose} ml
      Conducted by: ${this.vaccinator}
    `;
  }
}

// Examination and vaccination registry
class MedicalRegistry {
  private examinations: DinosaurExamination[] = [];
  private vaccinations: DinosaurVaccination[] = [];

  @LogOperation
  @ValidateExaminationDate
  registerExamination(
    examinationDate: Date,
    dinosaurId: string,
    temperature: number,
    weight: number,
    length: number,
    healthStatus: "Healthy" | "Light symptoms" | "Sick" | "Critical",
    notes?: string,
    examiner: string = "Dr. Harding"
  ): DinosaurExamination {
    const results: ExaminationResults = {
      temperature,
      weight,
      length,
      healthStatus,
      notes
    };

    const examination = new DinosaurExamination(dinosaurId, examinationDate, results, examiner);
    this.examinations.push(examination);

    console.log(`Examination registered: ${examination.examinationId} for dinosaur ${dinosaurId}`);

    return examination;
  }

  @LogOperation
  @ControlFrequency(90) // Minimum 90 days between vaccinations
  registerVaccination(
    dinosaurId: string,
    vaccinationDate: Date,
    genusVaccine: string,
    dose: number,
    vaccinator: string = "Dr. Harding"
  ): DinosaurVaccination {
    const vaccination = new DinosaurVaccination(
      dinosaurId,
      vaccinationDate,
      genusVaccine,
      dose,
      vaccinator
    );

    this.vaccinations.push(vaccination);

    console.log(`Vaccination registered: ${vaccination.vaccinationId} for dinosaur ${dinosaurId}`);

    return vaccination;
  }

  @Cache
  @LogOperation
  getExaminationHistory(dinosaurId: string): DinosaurExamination[] {
    console.log(`Fetching examination history for dinosaur ${dinosaurId}...`);

    // Simulating a long operation
    for (let i = 0; i < 500000; i++) {
      // CPU load
    }

    return this.examinations.filter(examination => examination.dinosaurId === dinosaurId)
      .sort((a, b) => b.examinationDate.getTime() - a.examinationDate.getTime());
  }

  @Cache
  @LogOperation
  getVaccinationHistory(dinosaurId: string): DinosaurVaccination[] {
    console.log(`Fetching vaccination history for dinosaur ${dinosaurId}...`);

    // Simulating a long operation
    for (let i = 0; i < 500000; i++) {
      // CPU load
    }

    return this.vaccinations.filter(vaccination => vaccination.dinosaurId === dinosaurId)
      .sort((a, b) => b.vaccinationDate.getTime() - a.vaccinationDate.getTime());
  }

  @MeasureExecutionTime
  @LogOperation
  generateMedicalReport(dinosaurId: string): string {
    const examinations = this.getExaminationHistory(dinosaurId);
    const vaccinations = this.getVaccinationHistory(dinosaurId);

    let report = `=== MEDICAL REPORT FOR DINOSAUR ${dinosaurId} ===\n\n`;

    report += `Number of examinations: ${examinations.length}\n`;
    report += `Number of vaccinations: ${vaccinations.length}\n\n`;

    if (examinations.length > 0) {
      const lastExamination = examinations[0];
      report += `LAST EXAMINATION:\n`;
      report += `Date: ${lastExamination.examinationDate.toLocaleString()}\n`;
      report += `Health status: ${lastExamination.results.healthStatus}\n`;
      report += `Temperature: ${lastExamination.results.temperature}ยฐC\n`;
      report += `Weight: ${lastExamination.results.weight} kg\n`;
      report += `Length: ${lastExamination.results.length} m\n`;
      if (lastExamination.results.notes) {
        report += `Notes: ${lastExamination.results.notes}\n`;
      }
      report += "\n";
    }

    if (vaccinations.length > 0) {
      const lastVaccination = vaccinations[0];
      report += `LAST VACCINATION:\n`;
      report += `Date: ${lastVaccination.vaccinationDate.toLocaleString()}\n`;
      report += `Vaccine type: ${lastVaccination.genusVaccine}\n`;
      report += `Dose: ${lastVaccination.dose} ml\n\n`;
    }

    report += `EXAMINATION HISTORY:\n`;
    examinations.forEach((examination, index) => {
      report += `${index + 1}. ${examination.examinationDate.toLocaleDateString()} - ${examination.results.healthStatus}\n`;
    });

    report += `\nVACCINATION HISTORY:\n`;
    vaccinations.forEach((vaccination, index) => {
      report += `${index + 1}. ${vaccination.vaccinationDate.toLocaleDateString()} - ${vaccination.genusVaccine}\n`;
    });

    return report;
  }
}

// Testing the system
const medicalRegistry = new MedicalRegistry();

// Registering examinations and vaccinations
try {
  // Past examination - OK
  const examination1 = medicalRegistry.registerExamination(
    new Date("2023-09-01"),
    "TREX-001",
    38.2,
    7500,
    12.5,
    "Healthy",
    "Routine examination",
    "Dr. Harding"
  );

  // Future examination - Error
  const examination2 = medicalRegistry.registerExamination(
    new Date("2025-01-01"), // future
    "TREX-001",
    39.1,
    7450,
    12.5,
    "Light symptoms",
    "Slight fever"
  );
} catch (error) {
  console.error(error.message);
}

// Registering vaccinations
try {
  // First vaccination
  const vaccination1 = medicalRegistry.registerVaccination(
    "TREX-001",
    new Date("2023-01-15"),
    "Dinosaur flu vaccine",
    50,
    "Dr. Sattler"
  );

  // Second vaccination - too early, should throw error
  const vaccination2 = medicalRegistry.registerVaccination(
    "TREX-001",
    new Date("2023-03-15"), // Only 60 days later, minimum is 90 days
    "Anti-parasite vaccine",
    30
  );
} catch (error) {
  console.error(error.message);
}

// Testing data retrieval
console.log(medicalRegistry.getExaminationHistory("TREX-001")); // Full fetch
console.log(medicalRegistry.getExaminationHistory("TREX-001")); // Uses cache

// Generating medical report
console.log(medicalRegistry.generateMedicalReport("TREX-001"));

In this elaborate example, we created a comprehensive system for managing dinosaur examinations and vaccinations in Jurassic Park, using various decorators:

  1. @UniqueID - ensures each examination and vaccination has a unique ID
  2. @LogOperation - logs method calls
  3. @ValidateExaminationDate - validates examination date correctness
  4. @ControlFrequency - ensures proper intervals between vaccinations
  5. @Cache - caches results of long-running operations
  6. @MeasureExecutionTime - measures report generation time

This system shows how method and property decorators can be used to create advanced business functionality while ensuring code consistency, data safety, and performance.

When to use method and property decorators

Method and property decorators are especially useful:

  1. When you want to add aspect-oriented functionality - logging, performance measurement, validation
  2. When you want to cache results - for computationally expensive methods
  3. When you need parameter validation - checking types, ranges, correctness
  4. When you want to control access - authorization, permission checking
  5. When you want to add metadata - for frameworks, ORMs, serialization
  6. When you need to monitor changes - tracking property changes

Limitations and issues

Like class decorators, method and property decorators have their limitations and issues:

  1. Harder debugging - code with many decorators can be harder to trace
  2. Typing problems - may require type casting (e.g., using as any)
  3. Hidden logic - implementation may be hidden in the decorator, making code harder to understand
  4. Application order - decorator order matters and can lead to subtle bugs
  5. Specification changes - the decorator specification is still evolving in JavaScript and TypeScript

Summary

Method and property decorators in TypeScript are powerful tools that allow adding extra functionality to class methods and properties in a declarative way. Just as operational protocols in Jurassic Park help control individual actions, method and property decorators help control and extend the behavior of individual class elements.

Thanks to decorators, we can create more modular, readable, and maintainable applications, isolating cross-cutting functionality such as logging, validation, or security. In large projects, well-designed decorators can significantly improve code quality and reduce redundancy.

However, like any advanced tool, method and property decorators should be used wisely. Excessive use of decorators can lead to code that is difficult to understand, debug, and test. The best practice is to use them where they genuinely provide benefits, not just for the sake of using them.

Code for this lesson: index.ts
// Method and property decorators - Supervising Jurassic Park operations
// Note: Decorators require "experimentalDecorators": true in tsconfig.json

// === METHOD DECORATOR - Logging operations ===
function LogOperation(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    console.log("[LOG] Call: " + propertyKey + "(" + args.join(", ") + ")");
    const startTime = Date.now();
    const result = originalMethod.apply(this, args);
    const duration = Date.now() - startTime;
    console.log("[LOG] Finished: " + propertyKey + " (" + duration + "ms)");
    return result;
  };

  return descriptor;
}

// === METHOD DECORATOR - Validating parameters ===
function ValidateSector(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    const sectorId = args[0];
    if (typeof sectorId !== "string" || !/^[A-Z]\d{1,2}$/.test(sectorId)) {
      throw new Error("Invalid sector: " + sectorId);
    }
    return originalMethod.apply(this, args);
  };

  return descriptor;
}

// === METHOD DECORATOR - Memoization (cache) ===
function Memoize(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  const cache = new Map<string, any>();

  descriptor.value = function (...args: any[]) {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      console.log("[CACHE] Cached result for " + propertyKey);
      return cache.get(key);
    }
    const result = originalMethod.apply(this, args);
    cache.set(key, result);
    return result;
  };

  return descriptor;
}

// === A CLASS WITH DECORATORS ===
class DinosaurTracker {
  private dinosaurs: Map<string, any> = new Map();

  constructor() {
    this.dinosaurs.set("A1", { name: "Rex", species: "T-Rex", health: 95 });
    this.dinosaurs.set("B3", { name: "Blue", species: "Velociraptor", health: 88 });
    this.dinosaurs.set("C2", { name: "Bronty", species: "Brachiosaurus", health: 100 });
  }

  @LogOperation
  @ValidateSector
  checkSector(sectorId: string): any {
    const dino = this.dinosaurs.get(sectorId);
    if (!dino) return { sector: sectorId, status: "empty" };
    return { sector: sectorId, ...dino, status: "active" };
  }

  @LogOperation
  @Memoize
  calculateFeedingCost(species: string, days: number): number {
    // Simulating expensive calculations
    const costs: Record<string, number> = {
      "T-Rex": 500,
      "Velociraptor": 200,
      "Brachiosaurus": 300,
    };
    return (costs[species] || 100) * days;
  }
}

// === TESTING ===
const tracker = new DinosaurTracker();

console.log("=== Checking sectors ===");
console.log(tracker.checkSector("A1"));
console.log(tracker.checkSector("B3"));

console.log("\n=== Feeding costs ===");
console.log("T-Rex 7 days:", tracker.calculateFeedingCost("T-Rex", 7));
console.log("T-Rex 7 days (cache):", tracker.calculateFeedingCost("T-Rex", 7));

console.log("\n=== Sector validation ===");
try {
  tracker.checkSector("invalid");
} catch (e: any) {
  console.error("Error:", e.message);
}

// TODO: Create a decorator @ReadOnly that prevents a method from being overwritten
// TODO: Create a decorator @Throttle(ms) that limits how often a method can be called

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which decorator in TypeScript receives the class constructor as an argument and can extend or replace it?

  2. 2. What three arguments does a method decorator receive in TypeScript in experimentalDecorators mode?

Hands-on tasks in the game

  • Code editor

    Implement the Trackable (class), Authorize (method), and MaxLength (property) decorators according to the instructions in the code.

  • Vertical ordering

    Order the steps for creating a method decorator in TypeScript (experimentalDecorators mode):

  1. QuestionTypes of Decorators
  2. QuestionMethod decorator
  3. Coding taskDecorators - Basic Practice
  4. Put in orderSteps to Create a Method Decorator

Useful articles