📘

Decorators: Enhancing Classes and Methods

Intermediate
110 XP
45 min
Lesson Content

Decorators in TypeScript

Decorators are a special syntax for modifying classes, methods, and properties. Essential for Angular framework.

Class Decorators

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

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
}

Method Decorators

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

class Calculator {
  @log
  add(a: number, b: number) {
    return a + b;
  }
}

Property Decorators

function readonly(target: any, propertyKey: string) {
  Object.defineProperty(target, propertyKey, {
    writable: false
  });
}

class User {
  @readonly
  name: string = "John";
}
Example Code

Understanding decorator syntax (Note: Decorators require experimental support)

// Decorators are experimental and require tsconfig setup
// For now, we'll show the concept

function log(target: any, propertyKey: string) {
  console.log(`Property ${propertyKey} defined`);
}

// In real TypeScript with decorators enabled:
// class Example {
//   @log
//   value: string;
// }

console.log("Decorators are used in Angular for dependency injection");

Expected Output:

Decorators are used in Angular for dependency injection
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code