TypeScript 装饰器

TypeScript 装饰器介绍

TypeScript 的装饰器主要是用于记录某些类型元信息和业务逻辑,装饰器不一定要实现实现业务逻辑,因为它的最大作用还是语法糖,以便代码和库的使用者可以方便地重用某些逻辑。装饰器的执行顺序是自上而下执行。接下来我们通过几个简单的例子看看 TypeScript 的装饰器是怎么使用的。

TypeScript 开启装饰器支持

TypeScript 的装饰器默认是关闭的,所以我们需要手动开启,具体代码如下:

"experimentalDecorators": true,

TypeScript 类装饰器

/**
 * 类装饰器只需传入目标类作为参数即可,然后就可以在目标类的基础上进行相应的操作
 */
function Component(target: Function) {
  target.prototype.id = 100;
}

@Component
export class TestClass {
  static elementId: string;
  id: number;

  printId(prefix: string = ""): string {
    return prefix + this.id;
  }
}

console.log(new TestClass().id);

或者可以传入相应的参数进行操作,例如:

function Component(option: { id: string }) {
  return (target: Function & typeof TestClass) => {
    target.elementId = option.id;
  };
}

@Component({ id: "200" })
export class TestClass {
  static elementId: string;
  id: number;

  printId(prefix: string = ""): string {
    return prefix + this.id;
  }
}

console.log(TestClass.elementId);

TypeScript 方法装饰器

/**
 * @param target 当前的原型对象
 * @param propertyKey 方法接受参数的关键字
 * @param propertyDesriptor 装饰器装饰的方法描述,
 */
function MethodTest(target: Object, propertyKey: string, propertyDesriptor: PropertyDescriptor) {
  console.log(target)
  console.log(propertyKey)
  console.log(propertyDesriptor)

  propertyDesriptor.value = function (...args: any[]) {
    return `Hello ${args}`
  }
}

@MethodTest
printId(prefix: string = ''): string {
  return prefix + this.id
}

TypeScript 属性装饰器

function PropTest(target: Object, propertyName: string) {
  let value: number;

  const getter = () => {
    console.log(`获取值${value}`);
    return value;
  };

  const setter = (newVal: number) => {
    console.log(`设置值${newVal}`);
    value = newVal;
  };

  Object.defineProperty(target, propertyName, { get: getter, set: setter });
}

@PropTest
id: number

TypeScript 方法参数装饰器

function MethodPropTest(target: Object, propertyName: string, index: number) {
  console.log('-------')
  console.log(target)
  console.log(propertyName)
  console.log(index)
  console.log('-------')
}

gateArea(width: number, @MethodPropTest height: number) {
  return width * height
}

实体代码下载

完整代码示例下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值