TypeScript装饰器

2021-01-18  本文已影响0人  黑曼巴yk

前言

装饰器分类

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

类装饰器

申明为:

declare type ClassDecorator = <TFunction extends Function>(
  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;

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

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 = <T>(target:Object, propertyKey: string | symbol,         
  descriptor: TypePropertyDescript<T>) => TypedPropertyDescriptor<T> | void;

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

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

上一篇下一篇

猜你喜欢

热点阅读