Difference Between Decorator and Function in Typescript

1. Introduction

In TypeScript, both decorators and functions play important roles but serve different purposes. A function is a set of statements that performs a task or calculates a value. A decorator, however, is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use functions to modify or annotate class declarations and members.

2. Key Points

1. Purpose: Functions perform tasks or calculations, decorators modify or annotate class-related code.

2. Usage: Functions are called explicitly, decorators are declared and affect the class or member they are attached to.

3. Syntax: Decorators are prefixed with an @ symbol.

4. Design Goals: Functions are designed for reusability and logic encapsulation, and decorators for meta-programming related to class declarations.

3. Differences

Characteristic Function Decorator
Purpose Perform tasks or calculations Modify or annotate classes and members
Usage Called explicitly Declared, affects where it is attached
Syntax Standard function call Prefixed with @ symbol
Design Goals Reusability, logic encapsulation Meta-programming, class modification

4. Example

// Example of a Function
function add(a: number, b: number): number {
    return a + b;
}

// Example of a Decorator
function sealed(constructor: Function) {
    Object.seal(constructor);
    Object.seal(constructor.prototype);
}

@sealed
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

Output:

Function Output:
add(2, 3) returns 5
Decorator Output:
The Greeter class is now sealed.

Explanation:

1. The add function is a standard function that takes two numbers and returns their sum.

2. The sealed decorator is applied to the Greeter class, modifying its behavior by sealing the class and its prototype.

5. When to use?

- Use functions for general-purpose tasks and logic encapsulation.

- Use decorators for meta-programming tasks, like modifying or annotating class declarations and members, often in frameworks or libraries.

Comments