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');
相关推荐
程序员黑豆2 小时前
鸿蒙应用开发教程:以红绿灯切换为例,掌握条件渲染的核心用法
前端·harmonyos
Catrice02 小时前
HarmonyOS ArkTS 实战:实现一个校园证件照拍摄与预约应用
华为·harmonyos
qizayaoshuap3 小时前
# [特殊字符] 手电筒 — 鸿蒙ArkTS设备功能调用与UI交互设计
ui·华为·交互·harmonyos
JaneConan3 小时前
鸿蒙报错速查:arkts-no-any any 类型禁用,用了就炸,根因 + 真解法
后端·harmonyos
listening7773 小时前
HarmonyOS 6.1 UX动效实战:从“生硬”到“灵动”的物理动画引擎
华为·harmonyos·ux
2301_768103495 小时前
HarmonyOS趣味相机实战第29篇:AudioRenderer合成快门声、并发门闩与资源释放
harmonyos·arkts·资源管理·音频开发·audiorenderer
listening7775 小时前
HarmonyOS 6.1 混沌工程实战:从“故障免疫”到“韧性架构”
华为·架构·harmonyos
特立独行的猫a5 小时前
Python三方库鸿蒙PC移植指南PPT
harmonyos·移植·鸿蒙pc·python三方库
程序员黑豆5 小时前
鸿蒙应用开发:ForEach 循环渲染用法详解
前端·harmonyos