</>
Skip to content
TypeScript lessons (26/31)

TypeScript — Decorators

Class decorator

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

@Sealed
class MyClass {
  property = 1;
}

Method decorator

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

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

Property decorator

function Validate(target: any, key: string) {
  let value: string;
  const getter = () => value;
  const setter = (newVal: string) => {
    if (newVal.length < 3) {
      throw new Error(`${key} must be at least 3 characters`);
    }
    value = newVal;
  };
  Object.defineProperty(target, key, { get: getter, set: setter });
}

class User {
  @Validate
  name!: string;
}

Mini Practice

Write TypeScript code that:

  1. Creates a class decorator
  2. Creates a method decorator
  3. Creates a property decorator
  4. Demonstrates decorator composition

Up Next

In the next lesson, you'll learn about Async Generators — async iteration.

Related Topics

Frequently Asked Questions about Decorators

What is Decorators in TypeScript?

Decorators is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Decorators?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Decorators.

Why is Decorators important in TypeScript?

Decorators is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.