Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Getting Started with ArkTS for HarmonyOS Development

Tech 1

ArkTS is the primary development language for HarmonyOS. Its syntax is highly similar to TypeScript, making it easy for front-end developers to adapt to with a low learning curve. Even if you have no prior TypeScript experience, you can start building HarmonyOS applications quickly by learning core common syntax first, before moving on to practicing with native components to build pages and full applications.

Environment Setup

Install Editor

You can set up the full development environment by installing Huawei's official DevEco Studio editor. Download the installer matching your operating system from the official site:
https://developer.huawei.com/consumer/cn/download/

Create New Project

After installation, launch the editor and select Create Project, then choose the Empty Ability template.

Enter your project name, set a local storage path for the project, select the latest available version for Compatible SDK (for example 5.0.0(12)). Leave Bundle name, Module name and Device type as default values for now, these only require adjustment when publishing the application later. Click Finish to generate the project.

The project entry file is src/main/ets/pages/Index.ets, all example code below will be added to this file.

Change Editor Language

If you prefer a Chinese interface, you can install the official Chinese localization plugin: Navigate to DevEco Studio > Preferences > Plugins, search for Chinese, install the plugin and restart the editor for changes to take effect.

Core Basic Syntax

Open entry/src/main/ets/pages/Index.ets, select Previewer from the top right corner of the editor, pick a simulator device, and click the run button to preview your code. You can overwrite the default auto-generated code when practicing, and check output from console.log() in the editor's log panel.

Variables and Constants

Variables and constants are used to store temporary data during program execution:

  • Use let to declare variables, which can be reassigned during runtime
  • Use const to declare constants, which cannot be modified after initialization, ideal for storing fixed values like configuration
let itemCount = 10;   // Mutable variable
const PI = 3.14; // Immutable constant

console.log(itemCount.toString())
console.log(PI.toString())

DevEco Studio requires values to be converted to strings for log output, hence the use of the .toString() method in the example.

Variable Types

ArkTS supports static typing, with multiple built-in data types including number, string, boolean, any, object, array and tuple. Explicit type declarations improve code readability and maintainability, and overuse of any is not recommended as it disables strict type checking.

Commonly used types:

  • Number: All numeric values, including integers and floating-point numbers
  • String: Text data, can be defined with single quotes, double quotes or backticks for template literals
  • Boolean: Logical values, only two possible values: true and false
  • Object: Complex data structures that store multiple key-value pairs
  • Array: Collections of elements that share the same type
  • Tuple: Fixed-length arrays with known element types, which can differ between positions

Explicit type declaration when creating variables follows this syntax:

let num: number = 42;
let greeting: string = "Hello, ArkTS!";
let isEnabled: boolean = true;

// Object with interface definition
interface UserProfile {
  name: string;
  age: number;
}
let user: UserProfile = { name: "Alice", age: 30 };

// Typed array
let scores: number[] = [1, 2, 3, 4];

// Typed tuple
let userTuple: [string, number] = ["Alice", 30];

Type Conversion

Use String(), Number(), Boolean() for explicit type conversion. Always account for implicit conversion behavior to avoid unexpected NaN or undefined results.

let numString = "123";
let convertedNum = Number(numString); // Converts input to numeric type

Operators

ArkTS supports all common arithmetic operators (+, -, *, /), comparison operators (===, !==) and logical operators (&&, ||). Using strict comparision operators avoids bugs caused by unintended implicit type conversion.

let sum = 5 + 10;       // Arithmetic addition
let isEqual = (5 === 5); // Strict equality check
let logicResult = (true && false); // Logical AND operation

Classes

Classes are the core building block of object-oriented programming, and can include properties, constructors and methods:

  • Properties: Store state for class instances
  • Constructors: Initialize new class instances
  • Methods: Define behavior for the class
// Define base class
class Animal {
  public name: string;

  constructor(name: string) {
    this.name = name;
  }

  makeSound(): void {
    console.log(`${this.name} makes a noise.`);
  }
}

// Extend base class
class Cat extends Animal {
  makeSound(): void {
    console.log(`${this.name} barks.`);
  }
}

// Create new instance
const myCat = new Cat("Luna");
myCat.makeSound(); // Output: Luna barks.

Conditional Branching

Use if, else if and else to implement conditional logic:

let age = 20
if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}

Loops

ArkTS supports multiple loop structures, including for loops and while loops:

for (let i = 0; i < 5; i++) {
  console.log(i.toString());
}

let j = 0;
while (j < 5) {
  console.log(j.toString());
  j++;
}

Functions

Use the function keyword to define functions, with support for typed parameters and return values:

function add(a: number, b: number): number {
  return a + b;
}

ArkTS also supports arrow function syntax:

let add = (a: number, b: number): number => a + b;

Enums

Enums are used to define a set of named constants, ideal for representing options with a fixed range of possible values:

enum Direction {
    Up,
    Down,
    Left,
    Right
}

let currentDir: Direction = Direction.Up;

Interfaces

Interfaces are used to define the required structure of objects:

interface Product {
  name: string;
  price: number;
}

let phone: Product = { name: "Huawei Pura 70", price: 4999 };

Generics

Generics allow functions or classes to handle multiple types while preserving type consistency. For example, you can use generics to create a function that keeps the parameter and return type the same, without restricting what type can be used:

function identity<T>(arg: T): T {
  return arg;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.