1 TypeScript 基础复习
ArkTS 脱胎于 TypeScript,扎实的 TS 基础是高效学习的前提
📦 类型系统
TypeScript 的核心价值在于静态类型检查——在编译阶段发现类型错误,而非运行时。
let name: string = "HarmonyOS";
let version: number = 5;
let isStable: boolean = true;
let id: string | number;
function greet(name?: string) {
return `Hello, ${name ?? 'World'}`;
}
💡 重点掌握:类型注解、联合类型、类型推断、null/undefined 处理
🔌 接口(Interface)
接口是 TypeScript 中定义对象结构的主要方式。ArkTS 中同样大量使用。
interface AppConfig {
name: string;
version: string;
permissions?: string[];
readonly appId: number;
}
const config: AppConfig = {
name: "MyApp",
version: "1.0.0",
appId: 10001
};
💡 扩展:extends 实现接口继承,Pick/Omit 工具类型
🧩 泛型(Generics)
泛型让你编写可复用的类型安全组件。在 ArkUI 的自定义组件中也常用到。
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
interface ListResponse<T> {
code: number;
data: T[];
total: number;
}
const res: ListResponse<string> = await fetchData();
💡 ArkTS 注意:ArkTS 对泛型约束更严格,不支持泛型类(class)——使用接口 + 函数组合替代。
3 开发环境与 Hello World
从 0 到 1:在你的 Mac 上跑起第一个鸿蒙应用
🖥️ 环境搭建流程
步骤 2 · 20分钟
下载并安装 DevEco Studio
官网下载 macOS 安装包,拖入 Applications 目录完成安装。首次启动会自动引导下载 HarmonyOS SDK,建议选择 API 14+ 版本。
步骤 3 · 10分钟
配置模拟器
Apple Silicon Mac 用户:推荐使用 Remote Emulator(华为云端模拟器),无需本地镜像,免费额度充足。
Intel Mac 用户:可安装 Local Emulator(x86 镜像)。
步骤 4 · 15分钟
创建第一个项目
File → New → Create Project → 选择 "Empty Ability" 模板 → 等待 Gradle 同步 → 点击 Run
📱 Hello World 工程结构
创建一个 Empty Ability 后,项目结构如下:
├── entry/
│ ├── src/main/
│ │ ├── ets/
│ │ │ ├── entryability/
│ │ │ │ └── EntryAbility.ets
│ │ │ └── pages/
│ │ │ └── Index.ets
│ │ ├── resources/
│ │ └── module.json5
│ └── build-profile.json5
├── oh_modules/
├── build-profile.json5
└── hvigor/
🚀 Hello World 代码
打开 Index.ets,默认的 Hello World 如下:
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Column() {
Text(this.message)
.fontSize(28)
.fontWeight(FontWeight.Bold)
.fontColor('#6c63ff')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
🧪 动手试试:将 message 改为你的名字,添加一个 Button 组件点击后改变文字。这会让你第一次感受到 ArkTS 声明式 UI 的"状态驱动"工作流。
🔍 常见环境问题排查
- Gradle 同步失败 → 检查网络代理,建议关闭 VPN 或配置 Gradle 国内镜像
- 模拟器连接超时 → Remote Emulator 需登录华为账号,检查网络是否屏蔽 huawei.com
- 代码报红但不影响编译 → DevEco Studio Lint 规则比编译更严格,检查是否使用了
any 类型
- 真机调试无法识别设备 → 开启开发者模式,授权调试,USB 连接使用 MTP 模式