재학습/NestJS

[NestJS] [데코레이터] 클래스 데코레이터

재삉 2023. 6. 18. 18:10
반응형

클래스 데코레이터

  • 클래스 바로 앞에 선언
  • 클래스의 생성자에 적용
  • 클래스의 정의를 읽거나 수정 가능
  • 선언파일과 선언클래스내에서는 사용불가능

 

구현

@reportableClassDecorator
export class ClassDecorationTest {
  type = 'report';
  title: string;

  constructor(t: string) {
    this.title = t;
  }
}

function reportableClassDecorator<T extends { new (...args: any[]) }>(
  constructor: T
) {
  return class extends constructor {
    reportingURL = 'http://www.example.com';
  };
}
  • 클래스데커레이터는 생성자를 리턴하는 함수다.

 

결과

  • reportingURL은 선언해주지도, 초기화하지도않았지만 객체결과로서 존재한다.
  • 클래스데코레이터를 통해 속성이 추가되었기 때문이다.
반응형