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 属性
相关推荐
Kitasan Burakku9 小时前
Typescript return type
前端·javascript·typescript
星光不问赶路人16 小时前
一文搞清楚 TypeScript 中 triple-slash 与 tsconfig.types 有何区别?
typescript·vite
duansamve4 天前
React 18+TS中使用Cesium 1.95
react.js·typescript·cesium
岁岁岁平安4 天前
SpringBoot3+WebSocket+Vue3+TypeScript实现简易在线聊天室(附完整源码参考)
java·spring boot·websocket·网络协议·typescript·vue
简小瑞5 天前
VSCode 源码解密:一个"无用"属性背后的精妙设计
typescript·visual studio code
FogLetter5 天前
TypeScript 泛型:让类型也拥有“函数式”超能力
前端·typescript
Keepreal4966 天前
Typescript中type和interface的区别
前端·typescript
huangql5206 天前
UniApp + Vite + Vue3 + TypeScript 项目中 ESLint 与 Prettier 的完整配置指南
vue.js·typescript·团队开发·代码规范
带娃的IT创业者6 天前
TypeScript + React + Ant Design 前端架构入门:搭建一个 Flask 个人博客前端
前端·react.js·typescript
星光不问赶路人7 天前
project references在tsserver内工作流程
typescript·visual studio code