DEV Community

Saulo Dias
Saulo Dias

Posted on

Understanding TypeScript Method Decorators

TypeScript provides decorators as a way to modify classes, methods, accessors, properties, or parameters at design time. Method decorators, in particular, allow you to intercept calls to methods within a class and modify their behavior or metadata.

What are Method Decorators?

Method decorators are functions that are prefixed with the @ symbol and placed immediately before a method declaration in a class. They can be used to modify the behavior of methods or to add metadata to them.

Syntax

const required: MethodDecorator = (
    target: Object,
    key: string | symbol,
    descriptor: TypedPropertyDescriptor<any>
) => {
    // Decorator logic here
}
Enter fullscreen mode Exit fullscreen mode
  • target: The prototype of the class for a static method, or the constructor function of the class for an instance method.
  • methodName: The name of the method being decorated.
  • descriptor: An object containing the property descriptor of the method being decorated.

Example: Required Property Decorator

Let's create a simple example to illustrate the usage of method decorators. Consider a scenario where we want to ensure that certain properties in a class are required and must be set before accessing them.

const required: MethodDecorator = (
    target: Object,
    key: string | symbol,
    descriptor: TypedPropertyDescriptor<any>
) => {
    const originalMethod = descriptor.get
    descriptor.get = function () {
        if (this[key] === undefined) {
            throw new Error(`Property ${String(key)} is required, but not set.`);
        }
        return originalMethod!.call(this);
    };
}

class MyClass {
    constructor(
        private readonly _name: process.env.NAME
    ) {}

    @required
    get name(): string {
        return this._name;
    }
}

// Set the environment variable
process.env.NAME = "John";

// Create the object
const myObject1 = new MyClass();
console.log(myObject1.name); // Outputs: "John"

// Delete the environment variable
delete process.env.NAME;

// Create another object
const myObject2 = new MyClass();
console.log(myObject2.name); // Throws an error since NAME is not set
Enter fullscreen mode Exit fullscreen mode

In this example, the required decorator ensures that the name property must be set before accessing it. If it's not set, an error is thrown.

Conclusion

Method decorators in TypeScript provide a powerful way to modify the behavior of methods or add additional functionality to them. They allow you to enforce certain rules or conditions on method access, add logging, caching, or any other cross-cutting concerns to your classes. Understanding decorators can greatly enhance the flexibility and maintainability of your TypeScript codebase.

Top comments (0)