TypeScript开启
在TypeScript中启用装饰器,你需要做以下几步:
- 确保你的
tsconfig.json
文件中包含了experimentalDecorators
选项,并且设置为true
。
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
- 安装Reflect元数据API的polyfill,因为TypeScript默认并不包含这个API。
npm install --save reflect-metadata
- 在你的代码的顶部导入
reflect-metadata
。
import 'reflect-metadata';
- 使用装饰器语法来装饰你的类、方法或属性。
import 'reflect-metadata';
// 定义一个简单的装饰器
function logClass(target: Function) {
console.log(`The class ${target.name} has been decorated.`);
}
// 应用装饰器到一个类
@logClass
class MyClass {
// 定义一个带参数的装饰器
@logProperty('id')
public id: number;
constructor(id: number) {
this.id = id;
}
// 定义一个方法装饰器
@logMethod
public getId(): number {
return this.id;
}
}
function logProperty(propertyKey: string) {
return (target: any, key: string) => {
console.log(`Property ${propertyKey} has been decorated.`);
};
}
function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log(`Method ${propertyKey} has been decorated.`);
}
const myInstance = new MyClass(1);
myInstance.getId();
在这个例子中,我们定义了一个类装饰器logClass
,一个属性装饰器logProperty
和一个方法装饰器logMethod
。然后我们在MyClass
类和其成员方法上应用了它们。当你运行这段代码时,你会看到控制台输出了相应的信息,证明装饰器已经按预期工作。
评论已关闭