Decorators בשפת TypeScript

Decorators בשפת TypeScript

Decorators הם תכונה חזקה ב- TypeScript שמאפשרת להוסיף מטא-דאטה ולשנות את ההתנהגות של מחלקות, מתודות, מאפיינים ופרמטרים. במאמר זה, נעמיק בעולם ה- Decorators, נבחן את סוגיהם השונים, ונספק דוגמאות קוד כדי להמחיש את השימוש בהם.

מה הם Decorators?

Decorators הם הצהרות מיוחדות שניתן לצרף למחלקה, מתודה, מאפיין או פרמטר. הם מספקים דרך להוסיף מטא-דאטה לקוד שלך ולשנות את התנהגותו באופן דינמי. ב- TypeScript, Decorators מופעלים על ידי הוספת הסימן @ לפני שם הפונקציה.

סוגי Decorators

ב- TypeScript ישנם מספר סוגי Decorators:

  1. Class Decorators
  2. Method Decorators
  3. Accessor Decorators
  4. Property Decorators
  5. Parameter Decorators

Class Decorators

Class Decorators מוחלים על מחלקה כולה. הם מוגדרים כפונקציה שמקבלת את הקונסטרקטור של המחלקה כפרמטר.

function Greeter(target: Function) {
    target.prototype.greet = function() {
        console.log('Hello from Greeter!');
    };
}

@Greeter
class MyClass {
    constructor() {}
}

const myClassInstance = new MyClass();
(myClassInstance as any).greet(); // Hello from Greeter!

Method Decorators

Method Decorators מוחלים על מתודות של מחלקה. הם מקבלים שלושה פרמטרים: target, propertyKey, ו- descriptor.

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

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

const calculator = new Calculator();
calculator.add(2, 3); // Calling add with arguments [2, 3]

Accessor Decorators

Accessor Decorators מוחלים על גטרים (getters) וסטרים (setters) של מחלקה.

function Enumerable(value: boolean) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.enumerable = value;
    };
}

class Person {
    private _name: string;

    constructor(name: string) {
        this._name = name;
    }

    @Enumerable(false)
    get name() {
        return this._name;
    }
}

const person = new Person('John');
console.log(person.name); // John

Property Decorators

Property Decorators מוחלים על מאפיינים של מחלקה. הם מקבלים שני פרמטרים: target ו- propertyKey.

function ReadOnly(target: any, propertyKey: string) {
    const descriptor: PropertyDescriptor = {
        writable: false
    };
    Object.defineProperty(target, propertyKey, descriptor);
}

class Car {
    @ReadOnly
    brand: string;

    constructor(brand: string) {
        this.brand = brand;
    }
}

const car = new Car('Toyota');
car.brand = 'Honda'; // TypeError: Cannot assign to read only property 'brand' of object

Parameter Decorators

Parameter Decorators מוחלים על פרמטרים של מתודות במחלקה. הם מקבלים שלושה פרמטרים: target, propertyKey ו- parameterIndex.

function LogParameter(target: any, propertyKey: string, parameterIndex: number) {
    const existingParameters = Reflect.getOwnMetadata('log_parameters', target, propertyKey) || [];
    existingParameters.push(parameterIndex);
    Reflect.defineMetadata('log_parameters', existingParameters, target, propertyKey);
}

class Library {
    greet(@LogParameter message: string) {
        console.log(message);
    }
}

const library = new Library();
library.greet('Hello, Decorators!'); // Hello, Decorators!

סיכום

Decorators ב- TypeScript הם כלי רב עוצמה שמאפשרים להוסיף מטא-דאטה ולשנות את התנהגות הקוד שלך באופן דינמי. במאמר זה סקרנו את הסוגים השונים של Decorators, כולל Class Decorators, Method Decorators, Accessor Decorators, Property Decorators ו- Parameter Decorators. כמו כן, סיפקנו דוגמאות קוד לכל סוג של Decorator כדי להמחיש את השימוש בהם.

הבנת השימוש ב- Decorators יכולה לשפר את הארגון והגמישות של הקוד שלך, ולהפוך את הפיתוח ב- TypeScript ליעיל ונוח יותר. אם יש לכם שאלות נוספות אתם מוזמנים להתייעץ איתנו, ואם אתם רוצים להעמיק את הידע אתם מוזמנים להתייעץ על קורס TypeScript.

בהצלחה!

שתפו את הפוסט

דילוג לתוכן