ホームページ  >  記事  >  ウェブフロントエンド  >  TypeScript のデコレータを理解する: 第一原理アプローチ

TypeScript のデコレータを理解する: 第一原理アプローチ

DDD
DDDオリジナル
2024-09-21 06:29:02942ブラウズ

Understanding Decorators in TypeScript: A First-Principles Approach

TypeScript のデコレーターは、クラス、メソッド、プロパティ、パラメーターの動作を変更するための強力なメカニズムを提供します。デコレータは現代の便利なように見えるかもしれませんが、オブジェクト指向プログラミングで見られる確立されたデコレータ パターンに根ざしています。デコレータは、ロギング、検証、アクセス制御などの一般的な機能を抽象化することで、開発者がよりクリーンで保守しやすいコードを作成できるようにします。

この記事では、デコレーターを第一原理から探求し、そのコア機能を分解して、ゼロから実装します。その過程で、日常の TypeScript 開発におけるデコレータの有用性を示す実際のアプリケーションをいくつか見ていきます。

デコレータとは何ですか?

TypeScript では、デコレーターは単にクラス、メソッド、プロパティ、またはパラメーターに付加できる関数です。この関数は設計時に実行されるため、コードの動作や構造を実行前に変更できます。デコレーターを使用するとメタプログラミングが可能になり、元のロジックを変更せずに機能を追加できるようになります。

メソッドが呼び出されたときにログを記録するメソッド デコレーターの簡単な例から始めましょう。

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

ここで、ログ デコレーターは、greet メソッドをラップし、実行前にその呼び出しとパラメーターをログに記録します。このパターンは、ロギングなどの横断的な関心事をコア ロジックから分離するのに役立ちます。

デコレータの仕組み

TypeScript のデコレータは、装飾しているアイテムに関連するメタデータを取り込む関数です。このメタデータ (クラス プロトタイプ、メソッド名、プロパティ記述子など) に基づいて、デコレーターは動作を変更したり、装飾されたオブジェクトを置き換えたりすることもできます。

デコレータの種類

デコレータは、それぞれ異なる目的を持つさまざまなターゲットに適用できます。

  • クラス デコレーター : クラスのコンストラクターを受け取る関数。
function classDecorator(constructor: Function) {
  // Modify or extend the class constructor or prototype
}
  • メソッド デコレーター : ターゲット オブジェクト、メソッド名、およびメソッドの記述子を受け取る関数。
function methodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  // Modify the method's descriptor
}
  • Property Decorators : ターゲット オブジェクトとプロパティ名を受け取る関数。
function propertyDecorator(target: any, propertyKey: string) {
  // Modify the behavior of the property
}
  • Parameter Decorators : ターゲット、メソッド名、パラメーターのインデックスを受け取る関数。
function parameterDecorator(target: any, propertyKey: string, parameterIndex: number) {
  // Modify or inspect the method's parameter
}

引数をデコレーターに渡す

デコレーターの最も強力な機能の 1 つは、引数を受け取る機能であり、デコレーターの動作をカスタマイズできます。たとえば、引数に基づいて条件付きでメソッド呼び出しをログに記録するメソッド デコレータを作成してみましょう。

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

logConditionally デコレータに true を渡すことで、メソッドがその実行を確実に記録します。 false を渡すと、ロギングはスキップされます。この柔軟性は、デコレータを多用途かつ再利用可能にする鍵となります。

デコレータの実世界への応用

デコレータは、多くのライブラリやフレームワークで実際に使用されています。以下に、デコレーターが複雑な機能を合理化する方法を示す注目すべき例をいくつか示します。

  • class-validator での検証: データ駆動型アプリケーションでは、検証は非常に重要です。 class-validator パッケージは、デコレーターを使用して、TypeScript クラスのフィールドを検証するプロセスを簡素化します。
import { IsEmail, IsNotEmpty } from 'class-validator';

class User {
  @IsNotEmpty()
  name: string;

  @IsEmail()
  email: string;
}

この例では、@IsEmail および @IsNotEmpty デコレーターにより、電子メール フィールドが有効な電子メール アドレスであり、名前フィールドが空ではないことが保証されます。これらのデコレータは、手動検証ロジックの必要性を排除することで時間を節約します。

  • TypeORM を使用したオブジェクト リレーショナル マッピング: デコレーターは、TypeORM などの ORM フレームワークで、TypeScript クラスをデータベース テーブルにマップするために広く使用されています。このマッピングは、デコレータを使用して宣言的に行われます。
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

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

  @Column()
  name: string;

  @Column()
  email: string;
}

ここで、@Entity、@Column、および @PrimaryGeneratedColumn は User テーブルの構造を定義します。これらのデコレータは SQL テーブル作成の複雑さを抽象化し、コードをより読みやすく、保守しやすくします。

  • Angular 依存関係の挿入: Angular では、デコレーターはサービスとコンポーネントの管理において重要な役割を果たします。 @Injectable デコレータは、他のコンポーネントまたはサービスに注入できるサービスとしてクラスをマークします。
@Injectable({
  providedIn: 'root',
})
class UserService {
  constructor(private http: HttpClient) {}
}

この場合の @Injectable デコレータは、UserService をグローバルに提供する必要があることを Angular の依存関係注入システムに通知します。これにより、アプリケーション全体でサービスをシームレスに統合できます。

独自のデコレータの実装: 内訳

デコレータは、本質的には単なる関数です。デコレータをゼロから作成するプロセスを詳しく見てみましょう:

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.

以上がTypeScript のデコレータを理解する: 第一原理アプローチの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。