티스토리 뷰

반응형

Typescript에서 Property Decorator란 클래스의 프로퍼티에 적용되는 데코레이터입니다.

데코레이터는 클래스, 메소드, 프로퍼티 등의 기능을 확장하거나 수정할 수 있습니다.

Property Decorator는 클래스의 프로퍼티에 적용되며, 프로퍼티를 변경하거나 다른 동작을 추가할 수 있습니다.

Property Decorator는 다음과 같은 형식으로 작성됩니다.

function propertyDecorator(target: Object, propertyKey: string | symbol) {
  // property decorator logic here
}

Property Decorator는 target, 즉 데코레이터가 적용되는 클래스 인스턴스를 가리키는 객체와, propertyKey, 적용되는 프로퍼티의 이름을 나타내는 문자열 또는 심볼을 매개변수로 받습니다.

Property Decorator를 사용하여 다양한 기능을 추가할 수 있습니다. 예를 들어, 유효성 검사기를 작성하여 프로퍼티의 값이 유효한지 확인할 수 있습니다.

function validate(target: Object, propertyKey: string | symbol) {
  let value = target[propertyKey];

  const getter = function() {
    return value;
  };

  const setter = function(newVal) {
    if (newVal < 0) {
      throw new Error("Value cannot be negative.");
    }

    value = newVal;
  };

  Object.defineProperty(target, propertyKey, {
    get: getter,
    set: setter
  });
}

class Example {
  @validate
  price: number;

  constructor(price: number) {
    this.price = price;
  }
}

const example = new Example(-10); // Throws Error

 

반응형

'타입스크립트' 카테고리의 다른 글

타입스크립트 Mixins  (0) 2023.03.17
타입스크립트 Parameter Decorator  (0) 2023.03.17
타입스크립트 Method Decorator  (0) 2023.03.17
타입스크립트 Class Decorator  (0) 2023.03.17
타입스크립트 Readonly 속성  (0) 2023.03.17
댓글