ArkTS 基础语法
编程语言介绍
什么是 ArkTS?
ArkTS 是 HarmonyOS 生态的应用开发语言。它基于 TypeScript(TS),并在此基础上进行了增强和优化,提供了声明式 UI 范式、状态管理支持等能力,帮助开发者以更简洁、自然的方式开发应用。ArkTS 强化了静态类型检查,支持并发编程增强,并与 TS/JS 生态高效互操作,兼容性良好。
ArkTS 的主要特点包括:
- 静态类型检查:在编译阶段检测更多错误,提升代码健壮性。
- 并发编程增强:优化了并发编程的支持,提升性能。
- 空值安全:通过类型系统减少空指针异常。
- 声明式 UI:提供声明式 UI 开发范式,简化 UI 开发。
ArkTS 基于 TypeScript 的增强
1. 强化静态类型检查
ArkTS 要求所有类型在程序运行前必须明确,减少运行时的类型检测,从而提升性能。
typescript
// TypeScript 允许动态类型推断
const area = {
pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: {
size: {
height: 1,
width: 2
},
x: 0,
y: 0
}
};
// ArkTS 中需要明确类型
import { image } from '@kit.ImageKit';
const area: image.PositionArea = {
pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: {
size: {
height: 1,
width: 2
},
x: 0,
y: 0
}
};
2. 限制运行时对象布局的修改
ArkTS 禁止在运行时动态修改对象的结构(如添加或删除属性),以确保性能优化。
typescript
// TypeScript 允许动态修改对象
class User {
name: string = '';
age: number = 20;
}
let user = new User();
(user as any).department = 'XX'; // 动态添加属性
delete (user as any).department; // 动态删除属性
// ArkTS 中需要在类定义时明确所有属性
class User {
name: string = '';
age: number = 20;
department?: string; // 可选属性
}
let user = new User();
user.department = 'XX'; // 正常赋值
user.department = undefined; // 置空可选属性
ArkTS 对 UI 的拓展
1. 声明式 UI 描述
ArkTS 提供了声明式 UI 开发范式,通过装饰器、自定义组件和内置组件,简化 UI 开发。
typescript
@Entry
@Component
struct MyComponent {
@State message: string = 'Hello, ArkTS!';
build() {
Column() {
Text(this.message)
.fontSize(20)
.onClick(() => {
this.message = 'Clicked!';
});
}
}
}
2. 状态管理
ArkTS 支持状态驱动 UI 更新,状态变化会自动触发 UI 重新渲染。
typescript
@State count: number = 0;
build() {
Column() {
Text(`Count: ${this.count}`)
.fontSize(20);
Button('Increment')
.onClick(() => {
this.count += 1; // 状态更新,UI 自动刷新
});
}
}
基本语法
变量与常量
- 使用
let
声明变量。 - 使用
const
声明常量。
typescript
let count: number = 0;
count = 10;
const MAX_COUNT: number = 100;
类型系统
基本类型
typescript
let name: string = 'Alice';
let age: number = 25;
let isActive: boolean = true;
enum Color {
Red,
Green,
Blue
}
let favoriteColor: Color = Color.Blue;
引用类型
typescript
let numbers: Array<number> = [1, 2, 3];
let names: string[] = ['Alice', 'Bob', 'Charlie'];
class Person {
name: string = '';
age: number = 0;
}
let person: Person = new Person();
联合类型与类型别名
typescript
let id: number | string = 123;
id = 'ABC';
type Point = {
x: number;
y: number;
};
let position: Point = { x: 10, y: 20 };
空值安全
ArkTS 通过类型系统避免空指针异常。
typescript
let name: string | null = null;
// 空值安全判断
if (name !== null) {
console.log(name.length);
}
// 空值合并运算符
const displayName = name ?? 'Unknown';
条件与循环
条件语句
typescript
let isReady: boolean = Math.random() > 0.5;
if (isReady) {
console.log('Ready!');
} else {
console.log('Not ready!');
}
let status = isReady ? 'Ready' : 'Not ready';
循环语句
typescript
let numbers: number[] = [1, 2, 3, 4, 5];
// for 循环
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// while 循环
let index = 0;
while (index < numbers.length) {
console.log(numbers[index]);
index++;
}
// for...of 循环
for (let num of numbers) {
console.log(num);
}
函数
函数声明
typescript
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}
greet('Alice');
箭头函数
typescript
const greet = (name: string) => console.log(`Hello, ${name}!`);
greet('Bob');
闭包
typescript
function createCounter(): () => number {
let count = 0;
return () => {
count++;
return count;
};
}
let counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
面向对象编程
类与对象
typescript
class Person {
name: string = '';
age: number = 0;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name}.`);
}
}
let person = new Person('Alice', 25);
person.greet();
继承与多态
typescript
class Employee extends Person {
department: string = '';
constructor(name: string, age: number, department: string) {
super(name, age);
this.department = department;
}
greet(): void {
super.greet();
console.log(`I work in ${this.department}.`);
}
}
let employee = new Employee('Bob', 30, 'Engineering');
employee.greet();
模块化
导出与导入
typescript
// person.ts
export class Person {
name: string = '';
age: number = 0;
}
// main.ts
import { Person } from './person';
let person = new Person();
person.name = 'Alice';
总结
ArkTS 是 HarmonyOS 生态的核心开发语言,基于 TypeScript 并进行了增强,提供了更强大的静态类型检查、并发编程支持和声明式 UI 开发能力。通过本文档的学习,您可以掌握 ArkTS 的基础语法和核心特性,为开发 HarmonyOS 应用打下坚实基础。