美文网首页
TypeScript装饰器

TypeScript装饰器

作者: 黑曼巴yk | 来源:发表于2021-01-18 11:01 被阅读0次

    前言

    装饰器分类

    • 类装饰器
    • 属性装饰器
    • 方法装饰器
    • 参数装饰器
      需要在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 - 属性描述符

    相关文章

      网友评论

          本文标题:TypeScript装饰器

          本文链接:https://www.haomeiwen.com/subject/siptzktx.html