Decorator

이 글에서는 TypeScript의 Decorator에 대해 알아보고, 설정 방법, 사용법, 합성, 그리고 Class Decorator에 대해 자세히 설명합니다.

Overview

Decorator는 Angular, Nest 등 많은 라이브러리/프레임워크에서 사용되고 있지만, 공식적으로 ECMAScript 에는 기재되지 않았다. ECMAScript 표준 스펙으로 들어갈 확률이 높기도 하고, 최근 읽었던 게시물 [ZUM] Zum portal Core JS을 읽고 (express 에 Custom Decorator 를 사용해서 Spring Boot 와 같은 프레임워크를 만든다) Decorator 에 대해 깊게 공부하고 싶다는 생각이 들었다. 이 글은 Typescript 공식 문서를 읽고 혼자 별도로 정리해본 글이다. (현재 experimental feature 이기 때문에, 미래에 기능이 변경될 가능성은 있다.)


Setting

Decorator 은 experomental feature 이기 때문에, 다음과 같이 설정해주어야 가능하다.

{
  "compilerOptions": {
    "target": "ES5",
    "experimentalDecorators": true
  }
}

or

tsc --target ES5 --experimentalDecorators

Decorators, Decorator Factories

decorators Decorator 는 1. class declaration 2. method 3. accessor 4. property 5. parameter 에붙일 수 있다. Decorator 는 초기 로드 시 evaluate 되고, 후에 런타임에서 호출된다. Decorator Factory 는 동적으로 Decorator 를 생성해주는 함수이다.

function factory(value: string) {
    // 아래 반환되는 Decorator 를 셋업하는 함수
    return function(target) {
        // 데코레이터.
    }
}

Decorator Composition

Decorator는 함수이기 때문에 합성이 가능하다. 합성은 수학에서의 function composition 과 동일하게 동작한다.

(f ∘ g)(x) is equivalent to f(g(x)).
  1. 합성된 함수들은 top -> bottom 순서로 evaluate 된다.
  2. 런타임에서 합성된 decorator 는 bottom -> top 으로 호출된다.
function first() {
  console.log("first(): factory evaluated");
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("first(): called");
  };
}

function second() {
  console.log("second(): factory evaluated");
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("second(): called");
  };
}

class ExampleClass {
  @first()
  @second()
  method() {}
}

위를 실행한 결과는 아래와 같다.

first(): factory evaluated
second(): factory evaluated
second(): called
first(): called

Class Decorator

Class Decorator 는 클래스의 생성자에 적용되며, 해당 클래스를 observe, modify, replace 할 수 있다. Class Decorator 는 클래스 선언(declare) 파일에서는 사용될 수 없다.

Contents

Overview Setting Decorators, Decorator Factories Composition Class Decorator

이것도 읽어보세요