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 属性
相关推荐
wuhen_n4 小时前
高阶函数与泛型函数的类型体操
前端·javascript·typescript
小学生波波11 小时前
HarmonyOS6 - 鸿蒙LED滚动字幕实战案例
arkts·鸿蒙·鸿蒙开发·harmonyos6·led滚动字幕
方方洛11 小时前
技术实践总结:schema-bridgion:json、xml、yaml、toml文件相互转换
xml·前端·typescript·node.js·json
We་ct12 小时前
LeetCode 28. 找出字符串中第一个匹配项的下标:两种实现与深度解析
前端·算法·leetcode·typescript
奔跑的web.14 小时前
TypeScript 类型断言
前端·javascript·typescript
We་ct1 天前
LeetCode 151. 反转字符串中的单词:两种解法深度剖析
前端·算法·leetcode·typescript
踢球的打工仔1 天前
typescript-接口的基本使用(一)
android·javascript·typescript
前端达人1 天前
为什么聪明的工程师都在用TypeScript写AI辅助代码?
前端·javascript·人工智能·typescript·ecmascript
EndingCoder1 天前
属性和参数装饰器
java·linux·前端·ubuntu·typescript
We་ct2 天前
LeetCode 14. 最长公共前缀:两种解法+优化思路全解析
前端·算法·leetcode·typescript