在 ArkTS(基于 TypeScript 的 HarmonyOS 开发语言)中,常见数据类型主要分为基础类型和复杂类型两大类,以下是核心整理:
⚙️ 一、基础类型(Primitive Types)
-
number
- 数值类型,包含整数和浮点数(无单独的
int
/float
区分)
initypescript 复制 let age: number = 30; // 整数 let price: number = 9.99; // 浮点数
- 数值类型,包含整数和浮点数(无单独的
-
string
- 文本类型,支持单引号/双引号/模板字符串
initypescript 复制 let name: string = "Alice"; let msg: string = `Hello ${name}`; // 模板字符串
-
boolean
- 布尔值,仅
true
或false
initypescript 复制 let isActive: boolean = true;
- 布尔值,仅
-
void
- 函数无返回值
javascripttypescript 复制 function logError(): void { console.error("Error!"); }
-
null
和undefined
null
:显式空值undefined
:变量未初始化默认值
csharptypescript 复制 let data: string | null = null; // 联合类型允许赋值为 null
🧩 二、复杂类型(Complex Types)
集合类型
-
数组
Array<T>
- 相同类型元素集合
typescripttypescript 复制 let numbers: number[] = [1, 2, 3]; let strings: Array<string> = ["a", "b"]; // 泛型语法
-
元组
Tuple
- 固定长度 和类型顺序的数组
typescripttypescript 复制 let userInfo: [string, number] = ["Alice", 25]; let firstElement: string = userInfo[0]; // 类型安全访问
-
枚举
enum
- 命名常量集合(自动赋值或手动指定)
initypescript 复制 enum Color { Red = 1, Green, Blue }; // Green=2, Blue=3 let bg: Color = Color.Green;
对象类型
-
接口
Interface
- 定义对象结构(最常用)
initypescript 复制 interface User { id: number; name: string; isAdmin?: boolean; // 可选属性 } let user: User = { id: 1, name: "Bob" };
-
类
Class
- 面向对象编程(封装/继承/多态)
typescripttypescript 复制 class Person { constructor(public name: string) {} greet() { console.log(`Hello ${this.name}`) } }
特殊类型
-
联合类型
|
- 变量可多选类型
initypescript 复制 let id: string | number; id = "001"; // 合法 id = 100; // 合法
-
字面量类型
- 固定值作为类型(常与联合类型配合)
initypescript 复制 type Direction = "left" | "right" | "up" | "down"; let move: Direction = "left"; // 只能赋值指定值
-
any
- 关闭类型检查(慎用!失去TS优势)
initypescript 复制 let unknownData: any = fetchExternalData();
-
Resource
(ArkUI特有)- 引用本地资源文件
lesstypescript 复制 Image($r('app.media.logo')) // 加载resources中的图片
🛡️ 三、类型守卫与类型推断
-
类型守卫
- 运行时检查类型(
typeof
/instanceof
)
typescripttypescript 复制 function printId(id: number | string) { if (typeof id === "string") { console.log(id.toUpperCase()); // 自动识别为string } else { console.log(id.toFixed(2)); // 自动识别为number } }
- 运行时检查类型(
-
类型别名
type
- 为复杂类型命名
initypescript 复制 type UserID = string | number; type Callback = () => void;
💎 核心数据类型总结表
类型 | 示例 | 典型场景 |
---|---|---|
number |
let count: number = 5; |
数值计算 |
string |
let msg: string = "Hi"; |
文本展示 |
boolean |
let isDone: boolean = false; |
条件判断 |
Array<T> |
let list: number[] = [1,2,3]; |
数据集合 |
Interface |
interface User { id: number } |
结构化数据定义 |
Union Types |
`let id: string | number;` |
Resource |
$r('app.string.title') |
本地化资源引用 |
实际开发建议:
- 优先使用接口定义对象结构
- 避免
any
充分利用TS静态检查- 联合类型+类型守卫提高安全性
- 善用资源类型加载本地文件