Class के Decorators
In this page:
function DecoratorName(constructor: Function) {
// modify or inspect the class
}
@DecoratorName
class ClassName {}
Basic Class Decorator
एक class decorator एक class declaration से directly पहले रखा जाता है और पूरी class को inspect या transform कर सकता है, class के constructor को इसके argument के रूप में receive करते हुए।
उदाहरण: Basic Class Decorator
function sealed(constructor: Function) {
console.log("Sealing class", constructor.name);
}
@sealed
class Account {
balance = 0;
}
new Account();
Class Initializers
Class decorators class body को directly modify किए बिना, class defined होने के ठीक बाद run होने के लिए additional logic schedule करने के लिए context.addInitializer call कर सकते हैं।
उदाहरण: Class Initializers
function withInit(target: any, context: ClassDecoratorContext) {
context.addInitializer(function (this: any) {
console.log("Initialized", this.constructor.name);
});
}
@withInit
class Service {}
new Service();
एक Class Replace करना
एक class decorator original class के compatible एक नया constructor return कर सकता है, effectively जहां भी इसे उपयोग किया जाता है वहां एक modified या wrapped version swap in करते हुए — cross-cutting behavior जोड़ने के लिए एक common pattern।
उदाहरण: Replacing a Class
function loggedClass<T extends { new (...args: any[]): {} }>(Base: T) {
return class extends Base {
constructor(...args: any[]) {
super(...args);
console.log("Created instance of", Base.name);
}
};
}
@loggedClass
class Widget {}
new Widget();
Class Decorator Factories
एक decorator factory एक function है जो खुद एक class decorator return करता है, इसे अपने arguments से configuration values capture करने देते हुए तो एक factory differently-configured decorators produce कर सकती है।
उदाहरण: Class Decorator Factories
function tag(name: string) {
return function (target: Function) {
console.log(`Tagging ${target.name} as ${name}`);
};
}
@tag("service")
class UserService {}
new UserService();
Multiple Class Decorators
एक ही class पर कई class decorators एक साथ apply किए जा सकते हैं; जब कई हों, तो decorator expressions एक specific, predictable order में evaluate और apply होते हैं।
उदाहरण: Multiple Class Decorators
function first(target: Function) {
console.log("first applied to", target.name);
}
function second(target: Function) {
console.log("second applied to", target.name);
}
@first
@second
class Example {}
new Example();
- एक plain decorator पर parentheses के साथ
@sealed()लिखना, जब call सिर्फ factories के लिए है। - यह भूल जाना कि एक class decorator class receive करता है, एक instance नहीं, तो
thisproperties अभी वहां नहीं हैं। - एक replacement class return करना जो original को extend नहीं करती, जो type compatibility तोड़ता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: