装饰器
原创2026/3/5大约 2 分钟
6.16 装饰器

装饰器就是一个方法,可以注入到一个类或方法甚至是属性和参数上来扩展他们的功能,使用装饰器不会破坏原有的结构
常见的装饰器有:类装饰器、属性装饰器、方法装饰器、参数装饰器
提示
由于装饰器目前处于实验阶段,必须在tsconfig.json配置文件中进行配置才可使用
"compilerOptions": {
"experimentalDecorators": true,
}类装饰器(无法参数)
// 装饰器
const fun1: ClassDecorator = (target: any) => {
console.log(target) // [class Person1]
target.prototype.name = 'lcl'
target.age = 20
}
@fun1 // 这里等同于第十一行
class Person1 {}
// fun1(Person1)
const p1 = new Person1()
// @ts-ignore // 跳过类型检查
console.log(p1.name)
// @ts-ignore
console.log(Person1.age)装饰器工厂(可传参)
const fun5 = (options: any) => {
return (target: any) => {
target.prototype.userName = options.name
target.age = options.age
}
}
@fun5({
name: '李四',
age: 18,
})
class Person5 {}
const p5 = new Person5()
// @ts-ignore // 跳过类型检查
console.log(p5.userName)
// @ts-ignore
console.log(Person5.age)装饰器组合
function demo1(target: any) {
console.log('demo1')
}
function demo2() {
console.log('demo2')
return (target: any) => {
console.log('demo2里面')
}
}
function demo3() {
console.log('demo3')
return (target: any) => {
console.log('demo3里面')
}
}
function demo4(target: any) {
console.log('demo4')
}
@demo1
@demo2()
@demo3()
@demo4
class Person {}
/*结果是:
demo2
demo3
demo4
demo3里面
demo2里面
demo1
*/属性装饰器
const fun2: PropertyDecorator = (target: Object, key: string | symbol) => {
console.log(target) // {}
console.log(key) // name
}
class Person1 {
@fun2
public name: string
constructor(name: string) {
this.name = name
}
}参数装饰器
const fun4: ParameterDecorator = (
target: Object,
key: string | symbol | undefined,
index: number,
) => {
console.log(target) // {}
console.log(key) // sayHi
console.log(index) // 1
}
class Person1 {
public name: string
constructor(name: string) {
this.name = name
}
sayHi(name: string, @fun4 age: string) {}
}方法装饰器
// 装饰器
const fun3: MethodDecorator = (target: Object, key: string | symbol, descriptor: any) => {
console.log(target) // {}
console.log(key) // sayHi
console.log(descriptor) // { value: [Function: sayHi], writable: true,enumerable: false,configurable: true}
}
class Person1 {
public name: string
constructor(name: string) {
this.name = name
}
@fun3
sayHi() {}
}至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。