typescript装饰器

81 阅读1分钟

类装饰器

const dec: ClassDecorator = (target: any) => {
  console.log(target)
}

@dec
class Human {
  constructor() {}
}

属性装饰器

const dec: PropertyDecorator = (target: any, key: string | symbol) => {
  console.log(target, key)
}

class Human {
  @dec
  public name: string
  constructor() {
    this.name = 'Tom'
  }
}

方法装饰器

const dec: MethodDecorator = (target: any, key: string | symbol, descriptor: any) => {
  console.log(target, key, descriptor)
}

class Human {
  public name: string
  constructor() {
    this.name = 'Tom'
  }

  @dec
  getName() {}
}

参数装饰器

const dec: ParameterDecorator = (target: any, key: string | symbol | undefined, parameterIndex: number) => {
  console.log(target, key, parameterIndex)
}

class Human {
  public name: string
  constructor() {
    this.name = 'Tom'
  }

  getName(@dec name: string) {}
}

案例

实现可传参的方法装饰器

import axios from 'axios'
 
const Get = (url: string): MethodDecorator => {
    return (target, key, descriptor: PropertyDescriptor) => {
        const fnc = descriptor.value;
        axios.get(url).then(res => {
            fnc(res, {
                status: 200,
            })
        }).catch(e => {
            fnc(e, {
                status: 500,
            })
        })
    }
}
 
//定义控制器
class Controller {
    constructor() {
 
    }
    @Get('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=10')
    getList (res: any, status: any) {
        console.log(res.data.result.list, status)
    }
  
}