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 属性
相关推荐
濮水大叔33 分钟前
在大型 Vue 项目中,如何有效管理复杂的状态?“散装版” vs “套装版”
前端·vue.js·typescript
谷哥的小弟1 天前
TypeScript数组类型
javascript·typescript
退休倒计时1 天前
【每日一题】LeetCode 199. 二叉树的右视图 TypeScript
算法·leetcode·typescript
前端之虎陈随易2 天前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·vue.js·人工智能·typescript·node.js
后台开发者Ethan2 天前
类型分类、联合类型、交叉类型
typescript
鹰影472 天前
一款AI笔记助手和远程同步的markdown笔记idea-note
人工智能·笔记·rust·typescript·react
想你依然心痛2 天前
AtomCode 在前端开发中的实战体验:React + TypeScript 项目开发实录
前端·react.js·typescript
疯狂的魔鬼2 天前
精确计算容器剩余视口高度:useAutoContainerFullHeight 的工程实践
前端·css·typescript
后台开发者Ethan2 天前
类型与变量
开发语言·typescript
孤狼warrior2 天前
从冒泡到传送带流水线:一个3D沉浸式算法靶场,让思想的伟力改变世界
python·算法·typescript