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');
相关推荐
OH_TPC9 小时前
【鸿蒙优选三方库】@ohos/mpchart:让 HarmonyOS 应用的数据可视化开箱即用
华为·信息可视化·harmonyos·鸿蒙
woshihuanglaoshi14 小时前
鸿蒙技术进阶全景高级成长体系:从初中级到架构师的技能树/学习路径/项目实战/认证体系系统性方法论
学习·华为·harmonyos
轻口味15 小时前
端侧 AI 赋能鸿蒙版 Obsidian:轻规划基于 HarmonyOS 7.0 图像超分特性的体验突破与开发实战
人工智能·华为·harmonyos·鸿蒙
OH_TPC16 小时前
【鸿蒙优选三方库】@ohos/lottie:让 After Effects 动画在 HarmonyOS 上稳定播放
华为·harmonyos·鸿蒙
李蚊子18 小时前
鸿蒙应用开发实践与上架复盘
harmonyos
2501_9197490319 小时前
华为鸿蒙训练口才APP—小羊口才
华为·harmonyos·鸿蒙
大锅盖119 小时前
HarmonyOS 摄像头焦点管理的完整工程实现
华为·harmonyos
woshihuanglaoshi21 小时前
鸿蒙老旧项目升级改造高级:API废弃迁移/ArkTS语法升级/架构重构策略/增量迁移/风险管控方案
学习·华为·重构·架构·harmonyos·鸿蒙
星空真迷人2 天前
嵌入式鸿蒙并非精简版,核心究竟是什么?
stm32·单片机·嵌入式硬件·物联网·华为·harmonyos·iot
OH_TPC2 天前
【鸿蒙优选三方库】@ohos/ijkplayer:在鸿蒙上像 B 站一样流畅播视频
华为·音视频·harmonyos·鸿蒙