学习TypeScript20(装饰器Decorator)

简介: 定义一个类装饰器函数 他会把ClassA的构造函数传入你的watcher函数当做第一个参数

Decorator 装饰器是一项实验性特性,在未来的版本中可能会发生改变


它们不仅增加了代码的可读性,清晰地表达了意图,而且提供一种方便的手段,增加或修改类的功能


若要启用实验性的装饰器特性,你必须在命令行或tsconfig.json里启用编译器选项


60df9a1067bf4dbd89d5a19897367f27.png


装饰器


装饰器是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上。


首先定义一个类


class A {
    constructor() {
    }
}


定义一个类装饰器函数 他会把ClassA的构造函数传入你的watcher函数当做第一个参数


const watcher: ClassDecorator = (target: Function) => {
    target.prototype.getParams = <T>(params: T):T => {
        return params
    }
}


使用的时候 直接通过@函数名使用


@watcher
class A {
    constructor() {
    }
}


验证


const a = new A();
console.log((a as any).getParams('123'));


装饰器工厂


其实也就是一个高阶函数 外层的函数接受值 里层的函数最终接受类的构造函数


const watcher = (name: string): ClassDecorator => {
    return (target: Function) => {
        target.prototype.getParams = <T>(params: T): T => {
            return params
        }
        target.prototype.getOptions = (): string => {
            return name
        }
    }
}
@watcher('name')
class A {
    constructor() {
    }
}
const a = new A();
console.log((a as any).getParams('123'));


装饰器组合


就是可以使用多个装饰器


const watcher = (name: string): ClassDecorator => {
    return (target: Function) => {
        target.prototype.getParams = <T>(params: T): T => {
            return params
        }
        target.prototype.getOptions = (): string => {
            return name
        }
    }
}
const watcher2 = (name: string): ClassDecorator => {
    return (target: Function) => {
        target.prototype.getNames = ():string => {
            return name
        }
    }
}
@watcher2('name2')
@watcher('name')
class A {
    constructor() {
    }
}
const a = new A();
console.log((a as any).getOptions());
console.log((a as any).getNames());


方法装饰器


返回三个参数


  1. 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
  2. 成员的名字。
  3. 成员的属性描述符。


[
  {},
  'setParasm',
  {
    value: [Function: setParasm],
    writable: true,
    enumerable: false,
    configurable: true
  }
]


const met:MethodDecorator = (...args) => {
    console.log(args);
}
class A {
    constructor() {
    }
    @met
    getName ():string {
        return '小满'
    }
}
const a = new A();


属性装饰器


返回两个参数


  1. 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
  2. 属性的名字。


[ {}, 'name', undefined ]


const met:PropertyDecorator = (...args) => {
    console.log(args);
}
class A {
    @met
    name:string
    constructor() {
    }
}
const a = new A();


参数装饰器


返回三个参数


  1. 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
  2. 成员的名字。
  3. 参数在函数参数列表中的索引。


[ {}, 'setParasm', 0 ]


const met:ParameterDecorator = (...args) => {
    console.log(args);
}
class A {
    constructor() {
    }
    setParasm (@met name:string = '213') {
    }
}
const a = new A();


元数据存储


import 'reflect-metadata'


可以快速存储元数据然后在用到的地方取出来 defineMetadata getMetadata


//1.类装饰器 ClassDecorator 
//2.属性装饰器 PropertyDecorator
//3.参数装饰器 ParameterDecorator
//4.方法装饰器 MethodDecorator PropertyDescriptor 'https://api.apiopen.top/api/getHaoKanVideo?page=0&size=10'
//5.装饰器工厂
import axios from 'axios'
import 'reflect-metadata'
const Base  = (base:string) => {
    const fn:ClassDecorator = (target) => {
        target.prototype.base = base;
    }
    return fn
} 
const Get = (url:string) => {
   const fn:MethodDecorator = (target:any,key,descriptor:PropertyDescriptor) => {
        axios.get(url).then(res=>{
            const key = Reflect.getMetadata('key',target)
            descriptor.value(key ? res.data[key] : res.data)
        })
   }
   return fn
}
const result = () => {
    const fn:ParameterDecorator = (target:any,key,index) => {
        Reflect.defineMetadata('key','result',target)
    }
    return fn
}
const Bt:PropertyDecorator = (target,key) => {
   console.log(target,key)
}
@Base('/api')
class Http {
    @Bt
    xiaoman:string
    constructor () {
        this.xiaoman = 'xiaoman'
    }
    @Get('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=10')
    getList (@result() data:any) {
        // console.log(data)
    }
    // @Post('/aaaa')
    create () {
    }
}
const http = new Http() as any
// console.log(http.base)


学习TypeScript21(Rollup构建TS项目)_qq1195566313的博客-CSDN博客

目录
相关文章
|
19天前
|
JavaScript 前端开发 数据安全/隐私保护
TypeScript中装饰器的概念与使用场景
【4月更文挑战第23天】TypeScript的装饰器是特殊声明,用于附加到类的声明、方法、属性或参数,以修改行为。它们以`@expression`形式,其中`expression`是运行时调用的函数。装饰器应用场景包括:日志记录、调试、依赖注入、权限控制和AOP。通过装饰器,可以实现动态行为修改,如添加日志、注入依赖、控制权限以及事务管理。然而,应谨慎使用,避免过度复杂化代码。装饰器在现代 TypeScript 开发中扮演重要角色,帮助编写更健壮、可维护的代码。
|
19天前
|
JavaScript 前端开发 编译器
TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)
TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)
77 0
|
19天前
|
存储 JavaScript 前端开发
TypeScript 5.2 beta 浅析:新的关键字 using 与新版装饰器元数据
TypeScript 5.2 beta 浅析:新的关键字 using 与新版装饰器元数据
|
19天前
|
编解码 JavaScript 前端开发
TypeScript【第三方声明文件、自定义声明文件、tsconfig.json文件简介、tsconfig.json 文件结构与配置】(六)-全面详解(学习总结---从入门到深化)
TypeScript【第三方声明文件、自定义声明文件、tsconfig.json文件简介、tsconfig.json 文件结构与配置】(六)-全面详解(学习总结---从入门到深化)
78 0
|
19天前
|
JavaScript
TypeScript【类的继承、访问修饰符、readonly 修饰符、存取器、实例方法与静态方法、实例属性与静态属性、静态属性、抽象类】(三)-全面详解(学习总结---从入门到深化)
TypeScript【类的继承、访问修饰符、readonly 修饰符、存取器、实例方法与静态方法、实例属性与静态属性、静态属性、抽象类】(三)-全面详解(学习总结---从入门到深化)
24 0
|
19天前
|
缓存 JavaScript 前端开发
【TypeScript技术专栏】TypeScript中的装饰器与元编程
【4月更文挑战第30天】TypeScript的装饰器是元编程工具,用于修改类、方法等行为。它们允许实现日志、权限控制、缓存等功能,支持类装饰器、方法装饰器等多种类型。装饰器借助JavaScript的Proxy和Reflection API实现,但过度使用可能造成复杂性。正确运用能提升代码质量,但需注意类型安全和维护性。
|
19天前
react+typescript装饰器写法报错的解决办法
react+typescript装饰器写法报错的解决办法
28 1
|
19天前
|
存储 JavaScript 前端开发
TypeScript笔记(15)—— 深入理解TypeScript中的装饰器
TypeScript笔记(15)—— 深入理解TypeScript中的装饰器
61 0
|
19天前
|
JavaScript
如何使用 TypeScript 创建和使用装饰器
如何使用 TypeScript 创建和使用装饰器
22 0
|
19天前
|
JavaScript 前端开发 编译器
TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)(下)
TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)
34 0
TypeScript【泛型1、泛型2、声明合并、命名空间 、模块1、模块2、声明文件简介】(五)-全面详解(学习总结---从入门到深化)(下)