这里的装饰器直接上代码了,如果是零基础请看TypeScript笔记中的“装饰器”章节
// 普通类装饰器(不可传参) const doc: ClassDecorator = (target: any) => { console.log(target) } @doc class Xiaoman { constructor() {} } // 类工厂装饰器(可自由传参) const docs = (str: string): ClassDecorator => { return (target: any): void => { console.log(str) } } @docs('这是一段字符串') class XiaomanFactory { constructor() {} } // 属性装饰器(返回构造函数和属性名) const props: PropertyDecorator = (target: any, key: string | symbol) => { console.log(target, key) } class XiaomanProperty { @props public name: string constructor() { this.name = '小满' } } // 方法装饰器(返回构造函数、方法名和方法定义) const method:MethodDecorator = (target: any, propertyKey: string | symbol,descriptor:any) => { console.log(target,propertyKey,descriptor); } class XiaomanMethod { constructor(){} @method getName(){} } // 参数装饰器(返回构造函数、参数名和参数所在位置(从前往后递减)) const param:ParameterDecorator = (target:any,propertyKey: string | symbol,parameterIndex: number) => { console.log(target,propertyKey,parameterIndex) } class XiaomanParams { constructor(){} myMethod(@param data:any,@param key:any){} } // 装饰器底层实现 class CustomXiaoman { constructor(){} } const custom = (target:any) => { console.log(target) } custom(CustomXiaoman)