← Back to TypeScript Course | Chapter 10: Decorators | Lesson 3 of 7

Method के Decorators

एक method decorator original method और एक ClassMethodDecoratorContext receive करता है। यह method को inspect कर सकता है, initialization logic register कर सकता है, या added behavior वाला एक replacement method return कर सकता है।
Syntax
typescript
function DecoratorName(target: any, key: string, descriptor: PropertyDescriptor) {
  // wrap descriptor.value
}

class ClassName {
  @DecoratorName
  method() {}
}

Basic Method Decorator

एक method decorator एक function है जो एक class method के ठीक ऊपर apply होता है जो target class, method name, और property descriptor receive करता है, इसे class instantiate होने से पहले भी उस method की definition को observe, modify, या replace करने देते हुए।

उदाहरण: Basic Method Decorator

typescript
function bound(target: any, context: ClassMethodDecoratorContext) {
  console.log("Decorating method:", String(context.name));
}
class Widget {
  @bound
  render() {
    return "rendered";
  }
}
new Widget().render();

Method Calls Log करना

Decorator के अंदर original method को wrap करना आपको method की अपनी body छुए बिना हर call के arguments और return value log करने देता है, जो logging जैसे cross-cutting concerns को business logic से अलग रखता है।

उदाहरण: Logging Method Calls

typescript
function logCall(target: any, context: ClassMethodDecoratorContext) {
  return function (this: any, ...args: any[]) {
    console.log(`Calling ${String(context.name)} with`, args);
    const result = target.call(this, ...args);
    console.log("Returned", result);
    return result;
  };
}
class Calculator {
  @logCall
  add(a: number, b: number) {
    return a + b;
  }
}
new Calculator().add(2, 3);

Method Arguments Validate करना

Descriptor के value function को intercept करके, एक decorator आने वाले arguments inspect कर सकता है और real method run होने से पहले throw कर सकता है, हर method के top पर checks repeat करने के बजाय आपको reusable validation देते हुए।

उदाहरण: Validating Method Arguments

typescript
function positiveOnly(target: any, context: ClassMethodDecoratorContext) {
  return function (this: any, ...args: any[]) {
    if (args.some((a) => typeof a === "number" && a < 0)) {
      throw new Error("Arguments must be positive");
    }
    return target.call(this, ...args);
  };
}
class Account {
  @positiveOnly
  deposit(amount: number) {
    return amount;
  }
}
console.log(new Account().deposit(100));

Method Initializers

कुछ decorators और आगे जाते हैं और method को पूरी तरह एक नए function से replace कर देते हैं जो internally original को call करता है, जो है कि memoization या automatic retries जैसे patterns मौजूदा methods पर कैसे bolt होते हैं।

उदाहरण: Method Initializers

typescript
function once(target: any, context: ClassMethodDecoratorContext) {
  let called = false;
  let result: any;
  return function (this: any, ...args: any[]) {
    if (!called) {
      result = target.call(this, ...args);
      called = true;
    }
    return result;
  };
}
class Loader {
  @once
  load() {
    console.log("Loading...");
    return "data";
  }
}
const loader = new Loader();
loader.load();
loader.load();

Method Decorator Factories

एक decorator factory एक function है जो एक method decorator return करता है, तो आप configuration (जैसे एक log level या एक retry count) decorator में ही pass कर सकते हैं एक fixed implementation में behavior hardcode करने के बजाय।

उदाहरण: Method Decorator Factories

typescript
function retry(times: number) {
  return function (target: any, context: ClassMethodDecoratorContext) {
    return function (this: any, ...args: any[]) {
      console.log(`Configured to retry ${times} times`);
      return target.call(this, ...args);
    };
  };
}
class Api {
  @retry(3)
  fetchData() {
    return "data";
  }
}
new Api().fetchData();
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Wrapper में एक arrow function उपयोग करना या this खो देना, तो original method गलत this के साथ call होता है।
  2. एक wrapping decorator में original method call करना (और इसका result return करना) भूल जाना, तो method silently कुछ नहीं करता।
  3. Decorator को class या एक property पर रखना बजाय उस method के ठीक ऊपर जिसे इसे wrap करना चाहिए।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.