TypeScript装饰器

前言

装饰器分类

  • 类装饰器
  • 属性装饰器
  • 方法装饰器
  • 参数装饰器
    需要在tsconfig.json中启用experimentalDecorators编译器的选项
{
  "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;

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

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

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

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 我想绝大多数开发人员都见识过 java 里的 annotation,经典的 @ 图标, 如 @Override: ...
    anOnion阅读 5,422评论 0 1
  • 参数装饰器 参数装饰器声明在一个参数声明之前(紧靠着参数声明)。 参数装饰器应用于类构造函数或方法声明。 参数装饰...
    2o壹9阅读 4,361评论 1 49
  • 访问器装饰器 访问器装饰器声明在一个访问器的声明之前(紧靠着访问器声明)。 访问器装饰器应用于访问器的 属性描述符...
    2o壹9阅读 4,717评论 1 49
  • 介绍 随着TypeScript和ES6里引入了类,在一些场景下我们需要额外的特性来支持标注或修改类及其成员。 装饰...
    2o壹9阅读 4,101评论 1 49
  • 什么是装饰器 装饰器是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上。 装饰器使用 @e...
    涅槃快乐是金阅读 30,748评论 3 17

友情链接更多精彩内容