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