首页 web前端 js教程 Understanding Decorators in TypeScript: A First-Principles Approach

Understanding Decorators in TypeScript: A First-Principles Approach

Sep 21, 2024 am 06:29 AM

Understanding Decorators in TypeScript: A First-Principles Approach

Decorators in TypeScript provide a powerful mechanism for modifying the behavior of classes, methods, properties, and parameters. While they may seem like a modern convenience, decorators are rooted in the well-established decorator pattern found in object-oriented programming. By abstracting common functionality like logging, validation, or access control, decorators allow developers to write cleaner, more maintainable code.

In this article, we will explore decorators from first principles, break down their core functionality, and implement them from scratch. Along the way, we'll look at some real-world applications that showcase the utility of decorators in everyday TypeScript development.

What is a Decorator?

In TypeScript, a decorator is simply a function that can be attached to a class, method, property, or parameter. This function is executed at design time, giving you the ability to alter the behavior or structure of code before it runs. Decorators enable meta-programming, allowing us to add additional functionality without modifying the original logic.

Let's start with a simple example of a method decorator that logs when a method is called:

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);
  };

  return descriptor;
}

class Example {
  @log
  greet(name: string) {
    return `Hello, ${name}`;
  }
}

const example = new Example();
example.greet('John');
登录后复制

Here, the log decorator wraps the greet method, logging its invocation and parameters before executing it. This pattern is useful for separating cross-cutting concerns like logging from the core logic.

How Decorators Work

Decorators in TypeScript are functions that take in metadata related to the item they are decorating. Based on this metadata (like class prototypes, method names, or property descriptors), decorators can modify behavior or even replace the decorated object.

Types of Decorators

Decorators can be applied to various targets, each with different purposes:

  • Class Decorators : A function that receives the constructor of the class.
function classDecorator(constructor: Function) {
  // Modify or extend the class constructor or prototype
}
登录后复制
  • Method Decorators : A function that receives the target object, the method name, and the method’s descriptor.
function methodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  // Modify the method's descriptor
}
登录后复制
  • Property Decorators : A function that receives the target object and the property name.
function propertyDecorator(target: any, propertyKey: string) {
  // Modify the behavior of the property
}
登录后复制
  • Parameter Decorators : A function that receives the target, the method name, and the index of the parameter.
function parameterDecorator(target: any, propertyKey: string, parameterIndex: number) {
  // Modify or inspect the method's parameter
}
登录后复制

Passing Arguments to Decorators

One of the most powerful features of decorators is their ability to take arguments, allowing you to customize their behavior. For example, let’s create a method decorator that logs method calls conditionally based on an argument.

function logConditionally(shouldLog: boolean) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

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

    return descriptor;
  };
}

class Example {
  @logConditionally(true)
  greet(name: string) {
    return `Hello, ${name}`;
  }
}

const example = new Example();
example.greet('TypeScript Developer');
登录后复制

By passing true to the logConditionally decorator, we ensure that the method logs its execution. If we pass false, the logging is skipped. This flexibility is key to making decorators versatile and reusable.

Real-World Applications of Decorators

Decorators have found practical use in many libraries and frameworks. Here are some notable examples that illustrate how decorators streamline complex functionality:

  • Validation in class-validator: In data-driven applications, validation is crucial. The class-validator package uses decorators to simplify the process of validating fields in TypeScript classes.
import { IsEmail, IsNotEmpty } from 'class-validator';

class User {
  @IsNotEmpty()
  name: string;

  @IsEmail()
  email: string;
}
登录后复制

In this example, the @IsEmail and @IsNotEmpty decorators ensure that the email field is a valid email address and the name field is not empty. These decorators save time by eliminating the need for manual validation logic.

  • Object-Relational Mapping with TypeORM: Decorators are widely used in ORM frameworks like TypeORM to map TypeScript classes to database tables. This mapping is done declaratively using decorators.
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}
登录后复制

Here, @Entity, @Column, and @PrimaryGeneratedColumn define the structure of the User table. These decorators abstract away the complexity of SQL table creation, making the code more readable and maintainable.

  • Angular Dependency Injection: In Angular, decorators play a pivotal role in managing services and components. The @Injectable decorator marks a class as a service that can be injected into other components or services.
@Injectable({
  providedIn: 'root',
})
class UserService {
  constructor(private http: HttpClient) {}
}
登录后复制

The @Injectable decorator in this case signals to Angular's dependency injection system that the UserService should be provided globally. This allows for seamless integration of services across the application.

Implementing Your Own Decorators: A Breakdown

Decorators are, at their core, just functions. Let’s break down the process of creating decorators from scratch:

Class Decorator

A class decorator receives the constructor of the class and can be used to modify the class prototype or even replace the constructor.

function AddTimestamp(constructor: Function) {
  constructor.prototype.timestamp = new Date();
}

@AddTimestamp
class MyClass {
  id: number;
  constructor(id: number) {
    this.id = id;
  }
}

const instance = new MyClass(1);
console.log(instance.timestamp);  // Outputs the current timestamp
登录后复制

Method Decorator

A method decorator modifies the method descriptor, allowing you to alter the behavior of the method itself.

function logExecutionTime(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    const start = performance.now();
    const result = originalMethod.apply(this, args);
    const end = performance.now();
    console.log(`${propertyKey} executed in ${end - start}ms`);
    return result;
  };

  return descriptor;
}

class Service {
  @logExecutionTime
  execute() {
    // Simulate work
    for (let i = 0; i < 1e6; i++) {}
  }
}

const service = new Service();
service.execute();  // Logs the execution time
登录后复制

Property Decorator

A property decorator allows you to intercept property access and modification, which can be useful for tracking changes.

function trackChanges(target: any, propertyKey: string) {
  let value = target[propertyKey];

  const getter = () => value;
  const setter = (newValue: any) => {
    console.log(`${propertyKey} changed from ${value} to ${newValue}`);
    value = newValue;
  };

  Object.defineProperty(target, propertyKey, {
    get: getter,
    set: setter,
  });
}

class Product {
  @trackChanges
  price: number;

  constructor(price: number) {
    this.price = price;
  }
}

const product = new Product(100);
product.price = 200;  // Logs the change
登录后复制

Conclusion

Decorators in TypeScript allow you to abstract and reuse functionality in a clean, declarative manner. Whether you're working with validation, ORMs, or dependency injection, decorators help reduce boilerplate and keep your code modular and maintainable. Understanding how they work from first principles makes it easier to leverage their full potential and craft custom solutions tailored to your application.

By taking a deeper look at the structure and real-world applications of decorators, you've now seen how they can simplify complex coding tasks and streamline code across various domains.

以上是Understanding Decorators in TypeScript: A First-Principles Approach的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1654
14
CakePHP 教程
1413
52
Laravel 教程
1306
25
PHP教程
1252
29
C# 教程
1225
24
前端热敏纸小票打印遇到乱码问题怎么办? 前端热敏纸小票打印遇到乱码问题怎么办? Apr 04, 2025 pm 02:42 PM

前端热敏纸小票打印的常见问题与解决方案在前端开发中,小票打印是一个常见的需求。然而,很多开发者在实...

神秘的JavaScript:它的作用以及为什么重要 神秘的JavaScript:它的作用以及为什么重要 Apr 09, 2025 am 12:07 AM

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

谁得到更多的Python或JavaScript? 谁得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

Python和JavaScript开发者的薪资没有绝对的高低,具体取决于技能和行业需求。1.Python在数据科学和机器学习领域可能薪资更高。2.JavaScript在前端和全栈开发中需求大,薪资也可观。3.影响因素包括经验、地理位置、公司规模和特定技能。

如何实现视差滚动和元素动画效果,像资生堂官网那样?
或者:
怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? 如何实现视差滚动和元素动画效果,像资生堂官网那样? 或者: 怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? Apr 04, 2025 pm 05:36 PM

实现视差滚动和元素动画效果的探讨本文将探讨如何实现类似资生堂官网(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的演变:当前的趋势和未来前景 JavaScript的演变:当前的趋势和未来前景 Apr 10, 2025 am 09:33 AM

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? 如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? Apr 04, 2025 pm 05:09 PM

如何在JavaScript中将具有相同ID的数组元素合并到一个对象中?在处理数据时,我们常常会遇到需要将具有相同ID�...

前端开发中如何实现类似 VSCode 的面板拖拽调整功能? 前端开发中如何实现类似 VSCode 的面板拖拽调整功能? Apr 04, 2025 pm 02:06 PM

探索前端中类似VSCode的面板拖拽调整功能的实现在前端开发中,如何实现类似于VSCode...

JavaScript引擎:比较实施 JavaScript引擎:比较实施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

See all articles