Typescript 클래스 데코레이터


TypeScript 클래스 데코레이터는 클래스 선언을 수정하는 함수입니다. 클래스 또는 클래스 구성원에 메타데이터를 추가하거나 클래스를 수정하는 데 사용됩니다. 이는 인스턴스를 만들기 전에 클래스의 동작을 변경하거나 클래스를 수정해야 할 때 유용합니다.

쉬운 목차

사용 방법

클래스 데코레이터는 클래스 선언 바로 앞에 위치하며 이렇게 @ 키워드 뒤에 데코레이터 함수를 작성하여 사용할 수 있습니다.

@decorator
class MyClass {}

다음 예제는 클래스를 변경하는 클래스 데코레이터를 보여줍니다. 이 예제는 클래스의 메서드가 실행될 때마다 콘솔에 로그를 인쇄합니다.

function logMethods(target: any) {
  // target.prototype에는 클래스의 프로토타입이 들어있습니다.
  const methods = Object.getOwnPropertyNames(target.prototype);

  for (let i = 0; i < methods.length; i++) {
    const methodName = methods(i);
    const originalMethod = target.prototype(methodName);

    // 새로운 함수를 만듭니다.
    const newMethod = function(...args: any()) {
      console.log(`Method ${methodName} called with arguments: ${args}`);

      // 원래의 메서드를 실행합니다.
      return originalMethod.apply(this, args);
    };

    // 새로 만든 함수로 원래의 메서드를 덮어씁니다.
    target.prototype(methodName) = newMethod;
  }
}

@logMethods
class MyClass {
  method1(arg1: string, arg2: number) {
    console.log('Method 1 called');
  }

  method2() {
    console.log('Method 2 called');
  }
}

const instance = new MyClass();
instance.method1('hello', 3);
instance.method2();

위의 코드를 실행하면 다음과 같은 결과가 나타납니다.

Method method1 called with arguments: hello,3
Method 1 called
Method method2 called with arguments:
Method 2 called

위의 코드에서 MyClass 클래스의 모든 메서드는 @logMethods 데코레이터 함수를 사용하여 선언됩니다.

각 호출에 대한 로그가 콘솔에 출력됩니다.