HarmonyOS 鸿蒙Next中,ArkTS如何定义Interface接口和Type类型?Record、泛型等如何使用?
HarmonyOS 鸿蒙Next中,ArkTS如何定义Interface接口和Type类型?Record、泛型等如何使用? 我在 ArkTS 项目中需要定义数据模型,想了解类型定义的最佳实践:
- 如何定义基础接口?可选属性(?)和只读属性(readonly)如何使用?
- 联合类型(|)和字面量类型如何限定取值范围?
- 泛型接口(Generic)如何定义通用的数据结构?
- Record<K, V> 类型如何定义动态键的对象?
- 接口继承(extends)如何实现类型复用?
希望能获取数据模型定义的完整代码示例。
实现思路:
- 定义基础接口,使用 ? 标记可选属性:
export interface CaseItem {
caseId: string;
title: string;
tags: string[];
createTime?: number; // 可选属性
}
- 使用联合类型和字面量类型限定取值范围:
type QuizType = 'single' | 'multiple' | 'judge';
export interface QuizQuestion {
type: QuizType; // 只能是指定的三个值
answer: string | string[]; // 联合类型
}
- 使用泛型接口定义通用数据结构:
interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
type CaseListResponse = ApiResponse<CaseItem[]>;
- 完整示例代码:
// model/CaseModel.ets
// 基础接口
export interface CaseItem {
caseId: string;
title: string;
phenomenon: string;
tags: string[];
createTime?: number;
updateTime?: number;
}
// 字面量类型
type Difficulty = 'easy' | 'medium' | 'hard';
type Responsibility = 'process' | 'equipment' | 'qa';
// 嵌套接口
export interface RootCause {
reason: string;
probability: number;
}
export interface FullCaseItem extends CaseItem {
rootCauses: RootCause[];
responsibility: Responsibility;
}
// 泛型接口
interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
// Record 类型:动态键的对象
export interface LearningProgress {
completedItems: string[];
categoryProgress: Record<string, {
bestScore: number;
examCount: number;
}>;
}
// 函数类型
interface SearchBarProps {
placeholder: string;
onSearch: (text: string) => void;
onClear?: () => void;
}
更多关于HarmonyOS 鸿蒙Next中,ArkTS如何定义Interface接口和Type类型?Record、泛型等如何使用?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在ArkTS中,使用interface关键字定义接口,例如interface Person { name: string }。使用type关键字定义类型别名,例如type ID = number | string。
Record<K, V>是内置工具类型,用于创建键类型为K、值类型为V的对象类型,例如Record<string, number>。
泛型在函数、类或接口中使用尖括号声明,例如function identity<T>(arg: T): T { return arg; }。接口也可使用泛型,如interface Box<T> { value: T }。
在ArkTS中,定义清晰的接口和类型是构建健壮数据模型的基础。以下是针对你问题的具体实现:
1. 基础接口定义
// 定义基础接口
interface User {
readonly id: number; // 只读属性,初始化后不可修改
name: string;
age?: number; // 可选属性
email: string;
}
// 使用示例
const user: User = {
id: 1,
name: "张三",
email: "zhangsan@example.com"
// age 是可选的,可以不提供
};
2. 联合类型与字面量类型
// 字面量类型限定特定值
type Status = 'active' | 'inactive' | 'pending';
type UserRole = 'admin' | 'user' | 'guest';
// 联合类型组合多种类型
type ID = number | string;
type ResponseData = string | number | boolean | object;
interface Order {
id: ID;
status: Status;
role: UserRole;
}
// 使用示例
const order: Order = {
id: "ORD-001", // 可以是字符串
status: 'active', // 只能是三个值之一
role: 'admin'
};
3. 泛型接口
// 定义泛型接口
interface ApiResponse<T> {
code: number;
message: string;
data: T;
timestamp: number;
}
// 定义分页数据泛型
interface PaginatedList<T> {
items: T[];
total: number;
page: number;
pageSize: number;
}
// 使用示例
interface Product {
id: number;
name: string;
price: number;
}
const productResponse: ApiResponse<Product> = {
code: 200,
message: "成功",
data: { id: 1, name: "手机", price: 2999 },
timestamp: Date.now()
};
const productList: PaginatedList<Product> = {
items: [
{ id: 1, name: "手机", price: 2999 },
{ id: 2, name: "平板", price: 1999 }
],
total: 2,
page: 1,
pageSize: 10
};
4. Record类型
// 使用Record定义动态键的对象
type UserScores = Record<string, number>;
// 更严格的键约束
type StatusMap = Record<'pending' | 'processing' | 'completed', number>;
// 使用示例
const scores: UserScores = {
'user1': 95,
'user2': 87,
'user3': 92
};
const statusCounts: StatusMap = {
pending: 5,
processing: 3,
completed: 12
};
// 复杂的Record使用
interface ProductInfo {
name: string;
price: number;
}
type ProductCatalog = Record<string, ProductInfo>;
const catalog: ProductCatalog = {
'p001': { name: '手机', price: 2999 },
'p002': { name: '平板', price: 1999 }
};
5. 接口继承
// 基础接口
interface BaseEntity {
readonly id: number;
createdAt: string;
updatedAt: string;
}
// 继承扩展
interface UserEntity extends BaseEntity {
username: string;
email: string;
isActive: boolean;
}
// 多层继承
interface AdminUser extends UserEntity {
permissions: string[];
role: 'super_admin' | 'admin';
}
// 使用示例
const userEntity: UserEntity = {
id: 1,
createdAt: "2024-01-01",
updatedAt: "2024-01-02",
username: "admin",
email: "admin@example.com",
isActive: true
};
const adminUser: AdminUser = {
...userEntity,
permissions: ['create', 'update', 'delete'],
role: 'super_admin'
};
6. 完整数据模型示例
// 类型定义
type Gender = 'male' | 'female' | 'other';
type UserStatus = 'active' | 'inactive' | 'suspended';
// 基础接口
interface Timestamp {
createdAt: string;
updatedAt?: string;
deletedAt?: string;
}
// 用户接口
interface User extends Timestamp {
readonly id: number;
username: string;
email: string;
age?: number;
gender: Gender;
status: UserStatus;
metadata?: Record<string, any>;
}
// 泛型响应接口
interface ApiResponse<T = any> {
success: boolean;
data: T;
error?: string;
pagination?: {
page: number;
pageSize: number;
total: number;
};
}
// 使用示例
const userData: User = {
id: 1,
username: "john_doe",
email: "john@example.com",
gender: "male",
status: "active",
createdAt: "2024-01-01T00:00:00Z",
metadata: {
lastLogin: "2024-01-02T10:30:00Z",
loginCount: 42
}
};
const apiResponse: ApiResponse<User> = {
success: true,
data: userData
};
这些示例覆盖了ArkTS中类型定义的主要场景。关键点包括:使用interface定义对象结构,type定义类型别名,readonly确保属性不可变,?标记可选属性,泛型提供类型灵活性,Record处理动态键对象,extends实现类型继承。

