TypeScript装饰器参数的类型、含义、顺序说明及官方文档查询请求
TypeScript装饰器的参数详解
没问题!TypeScript装饰器的参数会根据你装饰的目标(类、方法、属性等)不同而变化,下面按装饰类型逐个拆解参数的含义、排列顺序,还附上示例代码:
1. 类装饰器
类装饰器直接作用在类上,只有1个参数:
target: 被装饰类的构造函数(简单说就是这个类本身)
示例代码:
function ClassDecorator(target: Function) { console.log("被装饰的类构造函数:", target); } @ClassDecorator class MyClass {}
2. 方法装饰器
方法装饰器用于类的实例方法或静态方法,有3个参数,顺序固定:
target: 如果装饰的是静态方法,这是类的构造函数;如果是实例方法,这是类的原型对象propertyKey: 被装饰方法的名称(字符串或Symbol类型)descriptor: 方法的属性描述符,包含value(方法本身)、writable(是否可修改)等核心属性
示例代码:
function MethodDecorator( target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor ) { console.log("目标对象:", target); console.log("方法名称:", propertyKey); console.log("方法描述符:", descriptor); } class MyClass { @MethodDecorator myInstanceMethod() {} @MethodDecorator static myStaticMethod() {} }
3. 属性装饰器
属性装饰器用于类的实例属性或静态属性,有2个参数:
target: 静态属性对应类的构造函数,实例属性对应类的原型对象propertyKey: 被装饰属性的名称(字符串或Symbol类型)
注意:属性装饰器没有第三个参数,因为在TypeScript编译阶段无法获取到属性的描述符,这是由JavaScript的属性定义机制决定的。
示例代码:
function PropertyDecorator(target: any, propertyKey: string | symbol) { console.log("目标对象:", target); console.log("属性名称:", propertyKey); } class MyClass { @PropertyDecorator myInstanceProp: string; @PropertyDecorator static myStaticProp: number; }
4. 参数装饰器
参数装饰器用于方法的参数,有3个参数,顺序固定:
target: 静态方法的参数对应类的构造函数,实例方法的参数对应类的原型对象propertyKey: 包含该参数的方法名称(字符串或Symbol类型)parameterIndex: 该参数在方法参数列表中的索引(从0开始计数)
示例代码:
function ParamDecorator( target: any, propertyKey: string | symbol, parameterIndex: number ) { console.log("目标对象:", target); console.log("所属方法名:", propertyKey); console.log("参数索引:", parameterIndex); } class MyClass { myMethod(@ParamDecorator firstParam: string, @ParamDecorator secondParam: number) {} }
5. 访问器装饰器
访问器装饰器用于类的get/set访问器,参数和方法装饰器完全一致,共3个:
target: 静态访问器对应类的构造函数,实例访问器对应类的原型对象propertyKey: 访问器的名称descriptor: 访问器的属性描述符
注意:TypeScript不允许同时装饰一个成员的
get和set访问器,你只能选择其中一个装饰,装饰器会自动应用到该成员的所有访问器上。
示例代码:
function AccessorDecorator( target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor ) { console.log("目标对象:", target); console.log("访问器名称:", propertyKey); console.log("访问器描述符:", descriptor); } class MyClass { private _innerValue: string; @AccessorDecorator get value() { return this._innerValue; } set value(newVal: string) { this._innerValue = newVal; } }
关于官方文档,你可以在TypeScript官方文档的装饰器章节找到完整的规范和细节说明,里面还有更多关于装饰器执行顺序、元数据等进阶内容。
内容的提问来源于stack exchange,提问作者Platus
相关产品推荐
相关产品推荐

