TypeScript 装饰器详解

目录

装饰器

介绍

基本语法

类装饰器

方法装饰器

属性装饰器

参数装饰器

组合装饰器

装饰器工厂

总结


装饰器

介绍

TypeScript 中的装饰器(decorators)是一种特殊类型的声明,可以附加到类声明,方法,属性或参数上,以修改其行为。装饰器在编译阶段被应用,通常用来增强或修改类的行为或属性。

基本语法

在 TypeScript 中,装饰器以 @decoratorName 的形式使用,放置在装饰目标(如类、方法、属性等)的前面。装饰器可以是一个函数,接收不同的参数,具体参数取决于装饰的位置。

类装饰器

类装饰器在类声明之前声明,用来监视、修改或替换类定义。类装饰器可以接收一个参数,这个参数是被装饰的类本身。例如:

function classDecorator(constructor: Function) {
    console.log('Class decorator called.');
}

@classDecorator
class MyClass {
    // 输出:class implementation
}

上面的 classDecorator 函数就是一个类装饰器,它接收类的构造函数作为参数,并在类被定义时调用。类装饰器可以用来修改类的行为或元数据。

方法装饰器

方法装饰器用来监视、修改或替换方法定义。它接收三个参数:目标对象(对于静态成员是类的构造函数,对于实例成员是类的原型)、方法名和方法的属性描述符。例如:

function methodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log('Method decorator called.');
}

class MyClass {
    @methodDecorator
    myMethod() {
        // method implementation
    }
}

属性装饰器

属性装饰器用来监视、修改或替换类属性的定义。它接收两个参数:目标对象和属性名。例如:

function propertyDecorator(target: any, propertyKey: string) {
  console.log('Property decorator called.');
}

class MyClass {
  @propertyDecorator
  myProperty: string;
}

参数装饰器

参数装饰器应用于类构造函数或方法声明中的参数。它接收三个参数:目标对象、方法名或构造函数、参数在函数参数列表中的索引。例如:

function parameterDecorator(target: any, methodName: string, parameterIndex: number) {
  console.log('Parameter decorator called.');
}

class MyClass {
  myMethod(@parameterDecorator param1: string, @parameterDecorator param2: number) {
    //方法实现
  }
}

组合装饰器

装饰器可以组合使用,多个装饰器的执行顺序是从下到上,从右到左。例如:

function decorator1(target: any) {
    console.log('Decorator1');
}

function decorator2(target: any) {
    console.log('Decorator2');
}

@decorator1
@decorator2
class MyClass {
    // class implementation
}
// 输出:
// Decorator2
// Decorator1

装饰器工厂

装饰器可以接收参数并返回一个函数,以供装饰器在运行时调用。这种情况下被称为装饰器工厂。例如:

function myDecoratorFactory(name: string) {
    return function (target: any) {
        console.log(`Decorator called with name: ${name}`);
    };
}

@myDecoratorFactory('TestName')
class MyClass {
    // class implementation
}
// 输出:
// Decorator called with name: TestName

总结

装饰器是 TypeScript 中强大的功能之一,它允许我们在编译阶段静态地修改类的行为和属性。通过类装饰器、方法装饰器、属性装饰器和参数装饰器,我们可以实现各种复杂的逻辑和模式,使代码更具可读性和可维护性。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正在奋斗的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值