ArkTS is an extension of TypeScript designed for HarmonyOS application development. This chapter introduces ArkTS fundamentals, including constants and variables, comments, semicolons, types, scope, and other core concepts.
ArkTS uses const to declare constants that cannot be reassigned and let to declare variables that can be reassigned. Use const by default and switch to let only when reassignment is needed. This follows the principle of least privilege: data that is not intended to change should not be accidentally overwritten. const keeps the variable binding unchanged, but for objects it only locks the reference; properties inside the object can still be modified (for example, const arr = []; arr.push(1) is valid).
ArkTS uses let and const to declare variables and constants.
let count: number = 10; let name: string = 'ArkTS'; let isActive: boolean = true; // Reassignable let message: string = 'Hello'; message = 'Hello, ArkTS';
Unlike let, a binding declared with const cannot be reassigned. However, for reference types, the internal properties of the object can still be modified.
const MAX_SIZE: number = 100; const APP_NAME: string = 'MyApp'; // Constants must be initialized. const value: number = 10; // Correct. // Reference type: the reference remains unchanged, but the content can be modified. const numbers: number[] = [1, 2, 3]; numbers.push(4); // Valid. numbers = [5, 6]; // Compilation error.
An identifier consists of letters, digits, underscores, and $. It cannot start with a digit and cannot use reserved keywords. For naming conventions for variables, classes, constants, and other elements, see ArkTS Coding Style Guide.
// Valid naming let validName: number = 1; let _private: number = 2; let $special: number = 3; let camelCase: number = 4; // Invalid naming let 123start: number = 1; // Starts with a digit let my-var: number = 2; // Contains a hyphen let class: number = 3; // reserved keyword
The following keywords have special semantics in ArkTS and cannot be used as identifier names.
| Category | Keywords |
|---|---|
| Control flow | break case catch continue default do else finally for if of return switch throw try while |
| Declarations | class const declare enum export extends function import interface let type var |
| Modifiers and accessors | abstract get private protected public readonly set static |
| Operators and operations | delete in instanceof new super this typeof void |
| Values | false null true |
| Others | as async await debugger implements package with yield |
console provides multiple output methods: console.info for general information, console.warn for warnings, console.error for errors, and console.log for logs. console.info is an alias of console.log; both behave identically.
Using console.info is a coding style recommendation, not a language restriction. It keeps logging consistent with level-based method names such as console.warn and console.error and makes the logging intent clearer. During debugging, use template literals to include variable values or JSON.stringify to output objects.
let outputName: string = 'ArkTS';
const version: number = 1.0;
console.info(`${outputName}`); // 'ArkTS'
console.info(`${version}`); // 1
console.info(`Name: ${outputName}`); // 'Name: ArkTS'
console.info(`Version: ${version}, Name: ${outputName}`); // 'Version: 1, Name: ArkTS'
console.warn(`Version: ${version}, Name: ${outputName}`); // 'Version: 1, Name: ArkTS'
console.error('Invalid input'); // 'Invalid input' During debugging, select the corresponding method based on the information level, and use template strings or JSON.stringify to format complex object output.
ArkTS supports single-line comments (//) and multi-line comments (/* */) to explain the intent of the code.
A single-line comment starts with // and is used for brief explanations or temporarily disabling code.
let commentCount: number = 10; // Single-line comment
Multi-line comments are enclosed in /* */ and are used for detailed explanations or commenting out large blocks of code.
/*
* Multi-line comment
* Can span multiple lines*/
function calculate(): number {
return 100;
} Documentation comments are enclosed in /** */ and are used to generate API documentation and type hints.
/**
* Calculate the sum of two numbers.
* @param a The first number.
* @param b The second number.
* @returns The sum of the two numbers.
*/
function add(a: number, b: number): number {
return a + b;
} It is recommended to end each statement with a semicolon to improve code consistency and readability. When multiple statements are written on the same line, semicolons are required.
let x: number = 10;
let y: number = 20;
// Semicolons are required for multiple statements on the same line.
let a: number = 1; let b: number = 2;
// The semicolon at the end of a statement block is optional.
function greet(): void {
console.info('Hello');
} ArkTS provides basic data types such as number, boolean, and string to constrain value ranges and operations. For details about each data type, see Type System. For arrays, see Collection Types; for enums, see Enums.
Type declarations constrain the types of variables, parameters, and return values at compile time through type annotations, allowing the compiler to detect type mismatches (such as assigning a string to a number variable) before execution rather than at runtime. In addition to type annotations (: type) described below, ArkTS supports type aliases (type Name = ...) and interface declarations (interface). For details, see Type System and Interfaces.
Use type annotations (: type) to annotate types for variables, parameters, and return values.
// Variable type
let annotExAge: number = 0;
// Function parameter and return value types
function annotExGreet(name: string): string {
return `Hello, ${name}`;
}
// Class property type
class User {
public id: number = 0;
public name: string = '';
} Explicitly annotate public APIs and complex types (unions and generics). Simple local variables can rely on type inference (see Type Inference).
Type inference is the process by which the compiler automatically derives the type of a variable or expression from the context, without requiring you to explicitly annotate it. ArkTS supports type inference in most scenarios, and using it appropriately can reduce redundant annotations.
When a variable is assigned a value, the compiler infers the type of the variable from the value on the right side.
let tiCount = 10; // Inferred as number let tiMessage = 'hello'; // Inferred as string let tiItems = [1, 2, 3]; // Inferred as number[]
Variables declared with const are inferred as literal types, while variables declared with let are inferred as widened types.
const tiPi = 3.14; // Inferred as 3.14 (literal type). let tiRatio = 3.14; // Inferred as number (widened type).
When multiple candidate types exist, the compiler selects the most general type. If an array contains elements of multiple types (such as numbers mixed with null), ArkTS automatically infers the array literal as an array of the union of all element types (such as (number | null)[]), without an explicit annotation.
let tiMixed = [0, 1, null]; // Automatically inferred as (number | null)[]; no explicit annotation is needed. let tiNames: string[] = ['Alice', 'Bob']; // Inferred as string[].
If the type of an array element cannot be inferred (for example, an object literal without a type annotation), type inference fails. Explicitly annotate the array type, or apply a type assertion to the element before adding it to the array.
Scope determines the visibility and lifecycle of variables. ArkTS does not support var declarations. Declare variables using let and const, both of which have block scope. Function parameters, variables declared inside a function, and nested functions cannot be accessed outside the function, forming function scope.
Variables declared with let and const have block scope, cannot be accessed before their declaration, and cannot be redeclared in the same scope.
function blockScope(): void {
let bsA: number = 10;
const bsB: number = 20;
if (true) {
let bsA: number = 30; // An independent variable in the inner scope that does not affect the outer scope.
console.info(`${bsA}`); // 30
console.info(`${bsB}`); // 20, accessible from the outer scope.
}
console.info(`${bsA}`); // 10
} An inner scope can access outer variables, but not vice versa. let/const declarations in nested blocks can shadow outer variables with the same names.
let nsOuter: string = 'outer';
function nestedScope(): void {
let nsInner: number = 100;
console.info(`${nsOuter}`); // Accessible from the outer scope
if (true) {
let nsInner: number = 200; // Shadows the outer nsInner
console.info(`${nsInner}`); // 200
}
console.info(`${nsInner}`); // 100
}