TypeScript 装饰器

执行顺序

  1. 属性装饰器
  2. 方法装饰器
  3. 方法参数装饰器
  4. 类装饰器

如果同一个类型的装饰器有多个,总是先执行后面的装饰器。

less 复制代码
class NestedClass {
  @IsString()
  @exceedLength()
  name: string;

  constructor(props: any) {
    this.name = props.name;
  }
}

先执行exceedLength()再执行IsString()

类装饰器

可以为构造函数新增或修改变量或方法

typescript 复制代码
@reportableClassDecorator
class BugReport {
  constructor(t: string) {
    this.title = t;
    this._type = 'report';
  }
}


// 类装饰器
function reportableClassDecorator<T extends { new (...args: any[]): {}}>(constructor: T) {
  return class extends constructor {
    reportingURL = "http://www...";
    sayHello = () => {
        console.log('hello everyone');
    }
  }
}

interface BugReportV2 extends BugReport {
  reportingURL: string
  sayHello: () => void
}

const report = new BugReport("shanghai") as BugReportV2;

console.log(report.name);   // "http://www..." 
report.sayHello();					// "hello everyone"

属性装饰器

可以用于收集属性信息,也可以用来给类添加额外的方法和属性

通过元数据修改

更便捷的获取格式化数据

typescript 复制代码
import "reflect-metadata";
const formatMetadataKey = Symbol("format");

class BugReport {
  _type: string;
  title: string;
  @format("My name is %s")
  name: string = 'shenxin';

  constructor(t: string) {
    this.title = t;
    this._type = 'report';
  }

  introduceMyself() {
    const _tmpName = getFormat(this, 'name');
    return _tmpName.replace("%s", this.name);
  }
}

function format(formatString: string) {
  return Reflect.metadata(formatMetadataKey, formatString);
}
function getFormat(target: any, propertyKey: string) {
  return Reflect.getMetadata(formatMetadataKey, target, propertyKey);
}

interface BugReportV2 extends BugReport {
  reportingURL: string
  sayHello: () => void
}

const report = new BugReport("shanghai") as BugReportV2;

report.type = 'test';
report.name = "wangya";

console.log('name::: ', report.introduceMyself());  // "My name is wangya"

通过访问器修改

限制数据类型

typescript 复制代码
class NestedClass {
  @IsString()
  name: string;

  constructor(props: any) {
    this.name = props.name;
  }
}

function IsString() {
  return function (target: any, key: string) {
    let _key: string;
    Object.defineProperty(target, key, {
      get: () => _key,
      set: value => {
        if (typeof value !== 'string') {
          throw(`${key} must be a string`)
        }
        _key = value;
      }
    });
  }
}

const person = new NestedClass({
  name: 28,
});

console.log('person: ', person.name); // [ERR]: "name must be a string" 

方法装饰器

typescript 复制代码
class BugReport {
  _type: string;
  title: string;
  
  name: string = 'shenxin';

  constructor(t: string) {
    this.title = t;
    this._type = 'report';
  }
  
  @addHello
  getTitle() {
    return this.title;
  }
}


// 方法装饰器
function addHello(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const _getTitle = descriptor.value;
    
    descriptor.value = function() {
      return `hello ${_getTitle.bind(this)()}`;
    }
}


const report = new BugReport("shanghai");

console.log(report.getTitle());     // "hello shanghai"

访问器装饰器

typescript 复制代码
class BugReport {
  _type: string;
  title: string;
  name: string = 'shenxin';

  constructor(t: string) {
    this.title = t;
    this._type = 'report';
  }
  

  @addTmp
  set type(value: string) {
    this._type = value;
  }
  get type() {
    return this._type;
  }
}

// 访问器装饰器
function addTmp(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originSet = descriptor.set || function(){};

  descriptor.set = function(value: string) {
    // 获取方法参数
    return originSet.call(this, `this is ${value}`);
  }
}

const report = new BugReport("shanghai");

report.type = 'test';
console.log('report.type::: ', report.type);  // "this is test" 
相关推荐
不一样的少年_1 小时前
受够了当人肉传话筒:我把这 9 个 Agent 塞进了同一个聊天框
前端·agent·ai编程
狗头大军之江苏分军2 小时前
《潮水漫过十七岁》 加一个蛋,顺便说一下我解放了
前端·后端
Captaincc3 小时前
掘金AI用量迎来重大更新!全新AI用量
前端·后端
天若有情6733 小时前
开源|纯前端·条码&二维码在线生成器,支持拖拽缩放、复制生成码图片
前端·javascript·开源·html·二维码·条形码
map_vis_3d5 小时前
控制百度地图视野:setCenter、setZoom、panTo、flyTo 和 setViewport
前端·javascript·地图·百度地图
map_vis_3d5 小时前
百度地图 3D 视角:倾斜 tilt 与旋转 heading
前端·webgl·地图·百度地图·三维
Hilaku6 小时前
前端到底要不要写单元测试?
前端·javascript·程序员
ikoala6 小时前
每个独立开发者上线前,务必用这个skill做一次安全漏洞自查
前端·javascript·后端
anyup7 小时前
uni-app x 的 Signature 签名板与练字格,一个组件多端支持 App/鸿蒙/H5/小程序
前端·vue.js·uni-app
艾莉丝努力练剑7 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构