Annotation is a language feature of ArkTS that attaches structured metadata to declarations such as classes and methods. This chapter describes the declaration, usage, import and export, and source-state annotations.
Annotations are declared with @interface and used with the @ prefix to add metadata to declarations such as classes and methods.
Metadata describes code but is not part of program logic. Annotations do not change the runtime behavior of the annotated code; their value lies in allowing compilers and toolchains to read and process metadata. Information such as authors and versions written in comments cannot be recognized programmatically. Annotations attach this information to declarations in a structured form and are compiled along with the code. Typical scenarios include:
Annotations are an ArkTS extension and can be declared and used only in .ets and .d.ets files, not in .ts files. Annotations are not types and cannot be used as types or given type aliases; doing so causes a compilation error.
Annotations are declared with the @interface keyword and used with the @ prefix.
// Declare an annotation.
@interface ClassAuthor {
authorName: string;
}
// Use an annotation.
@ClassAuthor({authorName: "Bob"})
class MyClass {
// ...
} To use an annotation, its name must be prefixed with the symbol @ (for example, @MyAnno).
ClassAuthor({authorName: "Bob"}) // Compilation error: annotations must be prefixed with '@' A compilation error occurs if the annotation name is not accessible at the usage location.
Annotation declarations can be exported and used in other files.
Multiple annotations can be applied to the same declaration (the order of annotations does not affect their usage).
@MyAnno()
@ClassAuthor({authorName: "John Smith"})
class MyClass1 {
// ...
}
During app development, when a source HAR is built in release mode with obfuscation enabled at the same time, the build output is a JS file. Since JS has no annotation implementation mechanism, annotations are removed during compilation, making it impossible to implement AOP instrumentation through annotations.
To avoid functional exceptions caused by this, using annotations in a JS HAR (a HAR package whose build output contains JS) is prohibited.
If you need to build a HAR package containing annotations in release mode with obfuscation enabled, you can build a bytecode HAR.
The annotation declarations and uses in the preceding examples are in .ets source files. Annotations can also appear in .d.ets declaration files, where they are declared through ambient declarations.
ambientAnnotationDeclaration: 'declare' userDefinedAnnotationDeclaration ;
// NameAnno.d.ets
export declare @interface ClassAuthor3 {} In the preceding declaration:
// NameAnno.d.ets
export declare @interface NameAnno {name: string = ""} // MyAnno.ets
export @interface NameAnno {name: string = ""} // ok Like a class, an ambiently declared annotation can also be imported with import.
// NameAnno.d.ets
export declare @interface MyAnno {} // ImportMyAnno.ets
import { MyAnno } from './NameAnno';
@MyAnno
class C {
// ...
} Compiler-Generated .d.ets Files
When the compiler automatically generates .d.ets files from .ets code, the following two cases apply.
If an annotation definition is exported, it is retained in the .d.ets file.
// MyAnno.ets
export @interface ClassAuthor5 {}
@interface MethodAnno { // Not exported.
data: number;
} // NameAnno.d.ets
export declare @interface ClassAuthor5 {}
// Note: the unexported @interface MethodAnno does not appear in the generated .d.ets file. An annotation instance on a source-code entity is retained in the .d.ets file when all the following conditions hold.
// MyAnno.ets
import { ClassAuthor4 } from './Author';
export @interface MethodAnno4 {
data: number = 0;
}
@ClassAuthor4
export class MyClass {
@MethodAnno4({data: 123})
foo() {}
@MethodAnno4({data: 456})
private bar() {}
} // NameAnno.d.ets: declaration file generated by the compiler.
import { ClassAuthor4 } from './Author';
export declare @interface MethodAnno4 {
data: number = 0;
}
@ClassAuthor4
export declare class MyClass {
@MethodAnno4({ data: 123 })
foo(): void;
private bar; // Private methods retain no annotations and export no signatures; generated as private bar;
} User-Generated .d.ets Files
Annotation information in user-generated .d.ets files is not automatically applied to the implementation source code.
// NameAnno.d.ets Developer-generated declaration file
@interface ClassAuthor6 {}
@ClassAuthor6 // The declaration file contains an annotation.
class C {
// ...
} // MyAnno.ets Source code of the developer's implementation of the declaration file
@interface ClassAuthor6 {}
// No annotation in the implementation file.
class C {
// ...
} In the final compilation output, class C has no annotation.
The definition of a user-defined annotation is similar to that of an interface, except that the interface keyword is prefixed with @.
Annotation fields are limited to the following types:
The default value of an annotation field must be specified using a constant expression. The scenarios of constant expressions are as follows:
A compilation error occurs if the value of an enum cannot be determined at compile time.
function foo(): number {
return 1;
}
@interface Position {
data: number = foo(); // Compilation error: the default value of an annotation field must use a constant expression.
} An annotation must be defined in the top-level scope, and its name must not match any other entity name visible in that scope; otherwise, a compilation error occurs.
namespace ns {
@interface MetaInfo { // Compilation error: annotations must be defined in the top-level scope.
// ...
}
}
@interface Position {
// ...
}
class Position { // Compilation error: the name of an annotation cannot be the same as that of any other entity visible in the scope where the annotation is defined.
// ...
}
@interface ClassAuthor {
name: string;
}
@interface ClassAuthor { // Compilation error: the name of an annotation cannot be the same as that of any other entity visible in the scope where the annotation is defined.
data: string;
} An annotation is not a type. Using an annotation as a type causes a compilation error (for example, using a type alias for an annotation).
@interface Position {}
type Pos = Position; // Compilation error: annotations are not types. Annotations cannot be added to getter and setter methods of a class. Adding an annotation causes a compilation error.
@interface ClassAuthor {
authorName: string;
}
@ClassAuthor({authorName: 'John Smith'})
class MyClass {
private _name: string = 'Bob';
@ClassAuthor({authorName: 'John Smith'}) // Compilation error: annotations are not supported on getter and setter methods of a class.
get name() {
return this._name;
}
@ClassAuthor({authorName: 'John Smith'}) // Compilation error: annotations are not supported on getter and setter methods of a class.
set name(authorName: string) {
this._name = authorName;
}
} Currently, annotations can be used only on class declarations and method declarations. The same annotation can be used on both a class and a method. Annotations cannot be added to class getter or setter methods; doing so causes a compilation error.
@ClassPreamble({authorName: "John", revision: 2})
class C1 {
// ...
}
@ClassPreamble({authorName: "Bob"}) // The default value of revision is 1.
class C2 {
// ...
}
@MyAnno() // The same annotation can be used on both a class and a method.
class C3 {
@MyAnno()
foo() {}
@MyAnno()
static bar() {}
} The following is an example of an annotation declaration:
@interface ClassPreamble {
authorName: string;
revision: number = 1;
}
@interface MyAnno {} The order of fields in an annotation does not affect its use.
@interface ClassPreamble1 {
authorName: string;
revision: number = 1;
}
@ClassPreamble1({authorName: "John", revision: 2})
class C5 {}
// Equivalent to:
@ClassPreamble1({revision: 2, authorName: "John"})
class C6 {} When using an annotation, you must assign values to all fields that have no default values; otherwise, a compilation error occurs.
The assigned value must match the type declared in the annotation. Like the default value of an annotation field, the assigned value can only be a constant expression.
@ClassPreamble() // Compilation error: no value is assigned to the authorName field.
class C1 {
// ...
} If an annotation defines a field of array type, use an array literal to set the value of the field.
@interface ClassPreamble2 {
authorName: string;
revision: number = 1;
reviewers: string[];
}
@ClassPreamble2(
{
authorName: "Alice",
reviewers: ["Bob", "Clara"]
}
)
class C0 {
// ...
} If no annotation fields need to be defined, the parentheses after the annotation name can be omitted.
@MyAnno
class C4 {
// ...
} Annotations can also be imported and exported. For exporting, only exporting at the time of definition is currently supported, that is, in the form of export @interface.
// MyAnno.ets
export @interface MyAnno2 {}
export @interface ClassAuthor2 {} Only the following two import forms are currently supported:
// Annotation.ets
import { MyAnno2 } from './MyAnno';
import * as ns from './MyAnno';
// ...
@MyAnno2
@ns.ClassAuthor2
class C {
// ...
} Imports and exports have the following constraints:
Annotations cannot be renamed in import statements.
import { MyAnno as Anno } from './a'; // Compilation error: renaming an annotation in an import is not allowed. Because annotations are not types, importing and exporting them with the type symbol is not allowed.
import type { MyAnno } from './a'; // Compilation error: annotations cannot be imported or exported with the 'type' symbol Any other form of import/export for annotations is not allowed and causes a compilation error.
In addition, importing only annotations from a module does not trigger the module's side effects:
// MyAnno.ets
export @interface Anno {}
export @interface ClassAuthor1 {}
console.info('hello'); // Annotation.ets
import { Anno } from './MyAnno';
// Referencing only the Anno annotation does not execute console.info in MyAnno.ets. The same annotation cannot be used repeatedly on the same entity; otherwise, a compilation error occurs.
@interface MyAnno3 { name: string; value: number }
@MyAnno3({name: "123", value: 456})
@MyAnno3({name: "321", value: 654}) // Compilation error: duplicate annotations are not allowed.
class C {
// ...
} A subclass does not inherit the annotations of its base class, nor does it inherit the annotations of the base class methods.
Annotations are not supported on abstract classes or abstract methods; otherwise, a compilation error occurs.
@MyAnno3 // Compilation error: annotations are not allowed on abstract classes and abstract methods.
abstract class C {
@MyAnno3
abstract foo(): void; // Compilation error: annotations are not allowed on abstract classes and abstract methods.
} Starting from API version 24, you can define custom source-state annotations.
A source-state annotation is a special form of annotation. Its lifecycle exists only during compilation and does not affect the compilation output.
You can use the Retention API provided by ArkTS to construct a custom source-state annotation. A source-state annotation has a broader scope of use and can be applied to the following declarations:
The following shows how to declare and use a source-state annotation:
import { Retention, RetentionPolicy } from '@kit.ArkTS';
// Construct a user-defined source-state annotation.
@Retention({policy: RetentionPolicy.SOURCE})
@interface SourceAnnotation {}
// A source-state annotation can be used on classes and class members.
@SourceAnnotation
class C {
@SourceAnnotation
private name_: string = '';
@SourceAnnotation
get name(): string {
return this.name_;
}
}
// A source-state annotation can be used on variable declarations.
@SourceAnnotation
let a = 1;
// A source-state annotation can be used on interfaces and interface members.
@SourceAnnotation
interface I {
@SourceAnnotation
foo(): void
}
// A source-state annotation can be used on annotations.
@SourceAnnotation
@interface Anno {}
// A source-state annotation can be used on functions.
@SourceAnnotation
function func() {}
// A source-state annotation can be used on a namespace.
@SourceAnnotation
namespace ns {}
// A source-state annotation can be used on a type alias.
@SourceAnnotation
type A = number;
// A source-state annotation can be used on an enum.
@SourceAnnotation
enum ColorSet { RED, GREEN, BLUE }