TypeScript 泛型

TypeScript 泛型
一、泛型函数/方法
typescript 复制代码
// 定义
funName<T>(arg:T):T {
    return arg;
  }

// 调用
aboutToAppear(): void {
    this.funName<string>('aaa')
  }
二、泛型接口
typescript 复制代码
interface Comparator<T> {
  age:T
  compareTo(value:T): number;
}
三、泛型类
typescript 复制代码
class MyMap<K, V> {
  key: K;
  value: V;

  constructor(key: K, value: V) {
    this.key = key;
    this.value = value;
  }
}

鸿蒙需要给key,value初始化的。

也可以改为可选参数形式,就不用初始化了。

typescript 复制代码
class MyMap<K, V> {
  key?: K;
  value?: V;
  
}
四、泛型的类型别名
typescript 复制代码
type Box<T> = {
  content: T;
  isEmpty: boolean;
};

// 使用示例
const stringBox: Box<string> = {
  content: "Hello World",
  isEmpty: false
};

但鸿蒙api12后就不能这样定义了。api12后每个对象都要有具体类型

只好修改为接口的泛型

typescript 复制代码
interface Box<T> {
  content: T;
  isEmpty: boolean;
}

// 使用示例
const stringBox: Box<string> = {
  content: "Hello World",
  isEmpty: false
};
五、泛型的默认类型
typescript 复制代码
function getFirst<T = string>(
  arr:T[]
):T {
  return arr[0];
}

调用时可不指定类型,不指定就用string类型

六、泛型的约束
typescript 复制代码
// 约束接口 - 必须有 length 属性
interface Lengthwise {
  length: number;
}

// 泛型约束 - T 必须实现 Lengthwise 接口
function getLength<T extends Lengthwise>(arg: T): number {
  return arg.length;
}

// 使用示例
console.log(getLength("Hello")); // 5
console.log(getLength([1, 2, 3, 4, 5])); // 5
console.log(getLength({ length: 10, name: "test" })); // 10
// console.log(getLength(123)); // 错误:number 没有 length 属性
相关推荐
Orange_sparkle14 小时前
从五个 TypeScript 文件看懂 Coding Agent:一次 nano-pi 学习复盘
javascript·学习·typescript
深海鱼在掘金1 天前
深入浅出RAG——第7章:基础篇实战:文档问答机器人
人工智能·typescript·命令行
苏灿烤鱼1 天前
Cursor 官方插件仓,许可证未声明
typescript·agent·cursor
濮水大叔1 天前
CabloyJS 强大之处不仅仅是 IoC,而是全栈资源的寻址体系
typescript·node.js·全栈
To_OC2 天前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
mCell2 天前
用 Cordis 从零构建一个 Mini DeepSeek Harness
typescript·agent·deepseek
满栀5852 天前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
苏灿烤鱼2 天前
公司**不可计算,就自己做操作系统
rust·typescript·agent
sunly_2 天前
TypeScript总结:16、面向对象速查
前端·javascript·typescript
gs801402 天前
解构 Cordis:面向“时空可组合性”的 TypeScript 元框架深度剖析
前端·javascript·typescript