TS 的装饰器

发布时间 2023-03-29 17:35:06作者: makalo

官方文档

https://www.tslang.cn/docs/handbook/decorators.html

什么是装饰器

装饰器是一种特殊的类型声明,他可以附加在类,方法,属性,参数上面

类似于java 的注解

注意

要使用TS 的装饰器的 tsconfig.json,开启 experimentalDecorators的配置为true

例:

tsconfig.json:

{
    "compilerOptions": {
        "target": "ES5",
        "experimentalDecorators": true
    }
}

image-20230329164505854

类装饰器

主要是通过@符号添加装饰器

他会自动把class的构造函数传入到装饰器的第一个参数 target

然后通过prototype可以自定义添加属性和方法

// 他会自动把class的构造函数传入到装饰器的第一个参数 target
function decotators (target:any) {
    // 然后通过prototype可以自定义添加属性和方法
    target.prototype.name = 'makalo'
}

// 通过@符号添加装饰器
@decotators
class Makalo {
    // 将构造函数 传入 decotators 第一个参数
    constructor () {
 
    }
 
}
const makalo:any = new Makalo()
console.log(makalo.name)// makalo

image-20230329165852545

属性装饰器

同样使用@符号给属性添加装饰器

他会返回两个参数

1.原形对象

2.属性的名称

// 定义 currency 属性修饰器
const currency: PropertyDecorator = (target: any, key: string | symbol) => {
    // 返回原型对象和 属性名
    // Makalo2 {} name
    console.log(target, key)
}
class Makalo2 {
    // 属性修饰器
    @currency
    public name: string
    constructor() {
        this.name = ''
    }
    getName() {
        return this.name
    }
}

PropertyDecorator 类型描述

image-20230329171556148

参数装饰器

同样使用@符号给属性添加装饰器

他会返回两个参数

1.原形对象

2.方法的名称

3.参数的位置从0开始

const currency3: ParameterDecorator = (target: any, key: string | symbol,index:number) => {
    // Makalo3 {} getName 1
    console.log(target, key,index)
}
 
 
class Makalo3 {
    public name: string
    constructor() {
        this.name = ''
    }
    getName(name:string,@currency3 age:number) {
        return this.name
    }
}

方法装饰器

同样使用@符号给属性添加装饰器

他会返回两个参数

1.原形对象

2.方法的名称

3.属性描述符 可写对应writable,可枚举对应enumerable,可配置对应configurable

const currency4: MethodDecorator = (target: any, key: string | symbol,descriptor:any) => {
    console.log(target, key,descriptor)
}
 
 
class Makalo4 {
    public name: string
    constructor() {
        this.name = ''
    }
    @currency4
    getName(name:string,age:number) {
        return this.name
    }
}

image-20230329172502329