前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TypeScript系列教程十一《装饰器》 -- 参数装饰器

TypeScript系列教程十一《装饰器》 -- 参数装饰器

作者头像
星宇大前端
发布2022-05-06 17:21:24
5900
发布2022-05-06 17:21:24
举报
文章被收录于专栏:大宇笔记

系列教程

参数装饰器修饰函数参数,一般应用场景配合方法装饰器一起,达到检查参数的目的。

参数装饰器表达式会在运行时当作函数被调用,传入下列3个参数:

  • 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
  • 成员的名字。 -参数在函数参数列表中的索引。

下面通过例子具体查看。

代码示例

示例目的:

根绝参数器找到返回的值,然后利用方法装饰器返回处理后的结果。

代码思路

  1. 根据参数装饰器标识
  2. 通过reflect-metadata 将数据记载到方法元数据,然后传递到方法装饰器
  3. 方法装饰器调用原有方法返回值

代码实现

代码语言:javascript
复制
import "reflect-metadata";

const response: ParameterDecorator = (
  target: Object,
  propertyKey: string | symbol,
  parameterIndex: number
) => {
  Reflect.defineMetadata("response", parameterIndex, target, propertyKey);
};

const get: (path: string) => MethodDecorator = (path) => {
  return (
    target: Object,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor
  ) => {
    let originMethod = descriptor.value;
    let index = Reflect.getMetadata("response", target,propertyKey);        
    descriptor.value = function () {
       arguments[index] = {'data':'返回值'}
       let arr = []
       for (const eindex in arguments) {         
         if (Object.prototype.hasOwnProperty.call(arguments, eindex)) {
           const element = arguments[eindex];
           arr.push(element)
         }
       }       
       originMethod(...arr)
    };

  };
};

class HttpReq {
  @get("/getAllData")
  getAllData(request: {}, @response res?:{}) {
    console.log(res);
  }
}

let http =  new  HttpReq()
http.getAllData({'data':'requestBody'})

打印结果

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 系列教程
    • 代码示例
      • 示例目的:
      • 代码思路
      • 代码实现
      • 打印结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档