ArkTS支持TS5.0之前的TS装饰器语法。关于装饰器的定义和运行时行为,可以参考TS官方文档:https://www.typescriptlang.org/docs/handbook/decorators.htmlfunction TestClassDecorator(target: Function) { } function TestMemberDecorator(target: testClass, memberName: String) { } function TestFunDecorator(target: testClass, propertyName: String, descriptor: PropertyDescriptor) { } function TestArgDecorator(target: Function, methodName: String, paramIndex: Number) { } @TestClassDecorator class testClass { @TestMemberDecorator count: number = 123; @TestFunDecorator TestFun(@TestArgDecorator param: string) { } }注意,如果在ets文件中定义装饰器,则需要同时满足ArkTS的语法规则,比如不能使用any等。以下是类装饰器、属性装饰器、方法装饰器、参数装饰器的简单示例:自定义装饰器不支持装饰struct,可参考demo:// 类装饰器 function decorateKlass(target: ESObject) { console.log("decorateKlass") } @decorateKlass class Person { age: number = 12 } // 方法装饰器 export function MyDescriptor(target: Object, key: string, descriptor: PropertyDescriptor) { const originalMethod: Function = descriptor.value descriptor.value = (...args: Object[]) => { console.log(Calling ${target.constructor.name} method ${key} with argument: ${args}) const result: Object = originalMethod(...args) console.log(Method ${key} returned: ${result}) return result } return descriptor } @Entry @Component struct DecoratorDemo { @State message: string = 'Hello World'; aboutToAppear() { this.demo() } build() { Flex() { } .backgroundColor(Color.Green) .constraintSize({ minWidth: 100, maxWidth: 200, minHeight: 0, maxHeight: 200 }) .height('100%') } @MyDescriptor demo() { let person = new Person(); return person.age } }
ArkTS支持TS5.0之前的TS装饰器语法。关于装饰器的定义和运行时行为,可以参考TS官方文档:https://www.typescriptlang.org/docs/handbook/decorators.html
注意,如果在ets文件中定义装饰器,则需要同时满足ArkTS的语法规则,比如不能使用any等。以下是类装饰器、属性装饰器、方法装饰器、参数装饰器的简单示例:
自定义装饰器不支持装饰struct,可参考demo: