TypeScript装饰器

前言

装饰器分类

  • 类装饰器
  • 属性装饰器
  • 方法装饰器
  • 参数装饰器
    需要在tsconfig.json中启用experimentalDecorators编译器的选项
{
  "compilerOptions": {
     "target": "ES5",
     "experimentalDecorators": true
   }
}

类装饰器

申明为:

declare type ClassDecorator = (
  target: TFunction
) => TFunction | void;

其中target就是被装饰的类

function Greeter(target: Function): void {
  target.prototype.greet = function (): void {
    console.log("Hello Semlinker!");
  };
}

@Greeter
class Greeting {
  constructor() {
    // 内部实现
  }
}

let myGreeting = new Greeting();
myGreeting.greet(); 

如果是自定义的入参

function Greeter(greeting: string) {
  return function (target: Function) {
    target.prototype.greet = function (): void {
      console.log(greeting);
    };
  };
}

@Greeter("Hello TS!")
class Greeting {
  constructor() {
    // 内部实现
  }
}

let myGreeting = new Greeting();
myGreeting.greet();

属性装饰器

声明为:

declare type PropertyDecorator = (target:Object, 
  propertyKey: string | symbol ) => void;

属性装饰器,用来装饰类的属性,接受两个参数:

  • target: Object- 被装饰的类
  • propertyKey: string | symbol - 被装饰类的属性名
function logProperty(target: any, key: string) {
  delete target[key];

  const backingField = "_" + key;

  Object.defineProperty(target, backingField, {
    writable: true,
    enumerable: true,
    configurable: true
  });

  // property getter
  const getter = function (this: any) {
    const currVal = this[backingField];
    console.log(`Get: ${key} => ${currVal}`);
    return currVal;
  };

  // property setter
  const setter = function (this: any, newVal: any) {
    console.log(`Set: ${key} => ${newVal}`);
    this[backingField] = newVal;
  };

  // Create new property with getter and setter
  Object.defineProperty(target, key, {
    get: getter,
    set: setter,
    enumerable: true,
    configurable: true
  });
}

class Person { 
  @logProperty
  public name: string;

  constructor(name : string) { 
    this.name = name;
  }
}

const p1 = new Person("semlinker");
p1.name = "kakuqo";

方法装饰器

声明为:

declare type MethodDecorator = (target:Object, propertyKey: string | symbol,         
  descriptor: TypePropertyDescript) => TypedPropertyDescriptor | void;

用来装饰类的方法。它接收三个参数:

target: Object - 被装饰的类
propertyKey: string | symbol - 方法名
descriptor: TypePropertyDescript - 属性描述符

你可能感兴趣的:(TypeScript装饰器)