ArkTS 泛型概念详解

泛型是一种参数化多态技术,允许在定义函数、类或接口时使用类型参数代替具体类型,让类、函数、接口能适配多种数据类型,同时保持类型校验,避免重复编写相似逻辑。

泛型函数

function 函数名 <T> (参数:T): T {

函数体

}

ArkTS 复制代码
function identity<T>(arg: T): T {
  return arg;
}
// 使用方式,用作类型推断
let str = identity<string>('light');
let num = identity<number>(26);
let bool = identity<boolean>(true);

泛型类

class 类名 <T> {

属性名 T = 属性值

方法名 (): T {}

}

ArkTS 复制代码
class DeviceConfig<T> {
  private config: T | null = null; // 存储当前设备的配置

  setConfig(config: T): void {
    this.config = config;
    console.log(`${this.config} 配置完成:${JSON.stringify(config)}`);
  }
}

泛型接口

interface 接口名 <T> {

属性名 :T

方法名 : T

}

ArkTS 复制代码
interface  DeviceGroup<T> {
  groupName: string; // 群组名称,固定字段
  deviceList: T[]; // 不同类型的设备数组,泛型字段
}

泛型使用

泛型让函数、接口、类脱离具体类型约束,实现通用化编程。

ArkTS 复制代码
class Device<T> {
  private state: T;
  constructor(initialState: T) {
    this.state = initialState;
  }
  // 更新基本类型状态
  updateState(newState: T): void {
    this.state = newState;
    console.log('状态更新为:', this.state);
  }
}

// 使用:管理灯光开关(boolean类型)
let lightSwitch = new Device<boolean>(false);
lightSwitch.updateState(true); // 输出:状态更新为:true
// 使用:管理空调温度(number类型)
let acTemp = new Device<number>(26);
acTemp.updateState(28); // 输出:状态更新为:28

泛型约束

泛型约束是让泛型只能接收特定类型(或实现了特定接口)的参数,避免泛型被滥用,同时让编译器明确知道泛型拥有的能力,从而提供更精准的类型提示和安全校验。

ArkTS 复制代码
class DeviceQueue<T extends Device> {
  private devices: T[] = []; // 存储设备的数组,类型为 T[]
  // 入队:添加任意类型的设备
  enqueue(device: T): void {
    this.devices.push(device);
    console.log(`${JSON.stringify(device)} 已加入队列`);
  }
}

let stringQueue = new DeviceQueue<string>(); // 类型'string'不满足约束条件'Device'

泛型默认值

泛型默认值允许开发者在不显式指定类型参数时,为泛型类型或函数提供默认类型,从而简化代码并增强灵活性。

ArkTS 复制代码
class DeviceQueue<T = Device> {
  private devices: T[] = [];
  enqueue(device: T): void {
    this.devices.push(device);
    console.log(`${JSON.stringify(device)} 已加入队列`);
  }
}
class Device {
  name: string = '';
  constructor(name: string) {
    this.name = name;
  }
}
// 不显示指定泛型参数,使用默认值
let lightQueue = new DeviceQueue();
lightQueue.enqueue(new Device('空调设备'));
// 显示指定泛型参数为string
let stringQueue = new DeviceQueue<string>();
stringQueue.enqueue('ArkTS');
相关推荐
程序猿追15 小时前
kotlin-retry 接入鸿蒙后,怎样确认它真的会停止重试
开发语言·kotlin·harmonyos
懿路向前19 小时前
HarmonyOS 粒子特效实战:emitter.size 是双刃剑:粒子精确定位 [0,0] 与条带随机出生(HarmonyOS)
华为·harmonyos
马剑威(威哥爱编程)19 小时前
【共创稿事节】HarmonyOS 7 Agent 开发实战 04:云端 RAG 搭企业私有知识库问答
人工智能·华为·harmonyos
贾伟康20 小时前
【晨迹相机|20】HarmonyOS ArkTS AppGallery 发布复查实战:核对包名、版本、设备、素材和离线声明
harmonyos·arkts·appgallery·发布审核·上架复查
特立独行的猫a20 小时前
用仓颉写桌面应用:从 npx 建工程到串口实时示波器
开源·harmonyos·tauri·仓颉·cj-tarui
m0_685535081 天前
光学设计自学
华为·光学·光学设计·光学工程·镜头设计
懿路向前1 天前
HarmonyOS 粒子特效实战:马赛克切块提速 17.6×~38×:desiredRegion 重复读盘与一次解码管线(HarmonyOS)
华为·harmonyos
垆边人似月.1 天前
华为题:LRU 缓存
缓存·华为
天府云创1 天前
Agentic开发时代到来——鸿蒙PC三大原生开发工具公测
华为·操作系统·harmonyos·鸿蒙系统·cli·deveco·agentic
程序猿追1 天前
Fleks 鸿蒙适配:从八个小球看实体和组件的变化
华为·harmonyos