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');
相关推荐
HarmonyOS_SDK7 小时前
焕新鸿蒙应用权限管理方案,应用授权体验再升级
harmonyos
黑臂麒麟2 天前
HarmonyOS鸿蒙实战应用7:随手账本——数据导出与分享
华为·app·arkts·鸿蒙
贾伟康2 天前
【天体运行模拟|11】HarmonyOS ArkTS 收藏与笔记实战:同步知识页和个人学习记录
harmonyos·arkts·preferences·多设备适配·arkdata
2501_919749032 天前
华为鸿蒙录音可视化APP—小羊声觉
华为·harmonyos·鸿蒙
大雷神2 天前
HarmonyOS AR Engine深度估计实战——把毫米距离画成实时热力图
华为·ar·harmonyos
GKxx2 天前
在 HarmonyOS 上给 QEMU 搭一个最小 aarch64 Linux guest(内核 + busybox initramfs)
linux·华为·qemu·harmonyos·鸿蒙·鸿蒙pc
黑臂麒麟2 天前
屏幕信息全解析:HarmonyOS的分辨率、刷新率、折叠状态一个API搞定
华为·arkts·鸿蒙
黑臂麒麟2 天前
HarmonyOS 网络连接诊断实战:检测网络状态、WiFi 切换、弱网监测一网打尽
网络·华为·arkts·鸿蒙
贾伟康2 天前
【天体运行模拟|08】HarmonyOS ArkTS 单位换算实战:处理天文尺度、科学计数与精度
harmonyos·arkts·arkui·数值精度·单位换算
lilian2332 天前
HarmonyOS 7 新特性(十三)|3DGS 模型加载、交互与性能回退
3d·交互·harmonyos