재학습/NestJS

[NestJS] [데코레이터] 속성 데코레이터

재삉 2023. 6. 22. 18:26
반응형

속성 데코레이터

클래스의 속성 바로 앞에 선언

선언파일 선언클래스에서는 사용하지 못함

 

특징

두 개의 인수를 가지는 함수이다.

정적 멤버가 속한 클래스의 생성자함수이거나 인스턴스 멤버에 대한 클래스의 프로토타입

멤버의 이름

메서드 데커레이터, 접근자 데커레이터와 비교해 볼 때 속성 설명자가 존재하지않다는 특징이 있음

반환값 무시됨

 

구현

export class PropertyDecorationTest {
  @format('Hello')
  greeting: string;
}

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

    function getter() {
      return `${formatString} ${value}`;
    }

    function setter(newVal: string) {
      value = newVal;
    }

    return {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true,
    };
  };
}

 

propertyDeco(): string {
    const testInstance = new PropertyDecorationTest();
    console.log(testInstance.greeting);
    return 'property decorator test';
  }

실행 시

 

이를 수정해보자.

propertyDeco(): string {
    const testInstance = new PropertyDecorationTest();
    testInstance.greeting = 'World';
    console.log(testInstance.greeting);
    return 'property decorator test';
  }

결과

반응형