ts 泛型基础介绍

泛型:指的是,在定义函数/接口/类型...时,不预先指定具体的类型,而是在使用的时候再指定类型限制的一种特性


当我们定义一个变量,但不确定其类型的时候,有两种解决方式:

  1. 方式1:使用any
    使用any定义时存在的问题:虽然已知道传入值的类型,但是无法获取函数返回值的类型;另外也失去了ts类型保护的优势。
  2. 方式2:使用泛型
    泛型:在定义函数/接口/类型...时,不预先指定具体的类型,而是在使用的时候再指定类型限制的一种特性。

  1. 在函数中使用泛型
    使用方式:类似于函数传参,传什么数据类型,T就表示什么数据类型,使用时T也可以换成任意字符串
javascript 复制代码
function test<T>(arg: T): T {
  console.log('泛型=', arg)
  return arg
}
test<number>(123456) // 返回值是number类型的123456
test<string | boolean>('hahahaha') // 返回值是string类型的hahahaha
test<string | boolean>(false)

const test1 = <T>(arg: T): T => {
  console.log('泛型=', arg)
  return arg
}
const ret1 = test1<string>('Hello')
const ret2 = test1<number>(42)
const ret3 = test<number[]>([1, 2, 3])
  1. 在接口中使用泛型
javascript 复制代码
interface Search {
  <T, Y>(name: T, age: Y): T // 注意:这里写法是定义的方法哦。。。。。。
}

let fn: Search = function <T, Y>(name: T, id: Y): T {
  console.log(name, id)
  return name
}
fn('li', 11) // 编译器会自动识别传入的参数,将传入的参数的类型认为是泛型指定的类型

  1. 使用接口约束泛型
javascript 复制代码
interface Person {
 zname: string
 zage: number
}
function student<T extends Person>(arg: T): T {
 return arg
}
// 例子1:传入满足 Person 接口的对象
const person: Person = { zname: 'Alice', zage: 25 }
const result1 = student(person) // 返回类型为 Person

// 例子2:传入满足 Person 接口的子类型的对象
class Student implements Person {
 zname: string
 zage: number
 constructor(name: string, age: number) {
   this.zname = name
   this.zage = age
 }
}
const studentObj = new Student('Bob', 30)
const result2 = student(studentObj) // 返回类型为 Student

// 例子3:传入不满足 Person 接口的对象
const invalidObj = { zname: 'Charlie', zage: '20' } // 注意:zage 的类型错误
// const result3 = student(invalidObj); // 报错:类型 "{ zname: string; zage: string; }" 的参数不能赋给类型 "Person" 的参数

// 例子4:传入不满足 Person 接口的对象,但使用类型断言绕过类型检查
// const invalidObj2 = { zname: 'Charlie', zage: '20' } as Person; // 使用类型断言
// const result4 = student(invalidObj2); // 返回类型为 Person
相关推荐
duandashuaige6 小时前
解决用electron打包Vue工程(Vite)报错electron : Failed to load URL : xxx... with error : ERR _CONNECTION_REFUSED
javascript·typescript·electron·npm·vue·html
Damon小智13 小时前
仓颉 Markdown 解析库在 HarmonyOS 应用中的实践
华为·typescript·harmonyos·markdown·三方库
熊猫钓鱼>_>1 天前
TypeScript前端架构与开发技巧深度解析:从工程化到性能优化的完整实践
前端·javascript·typescript
敲敲敲敲暴你脑袋1 天前
Canvas绘制自定义流动路径
vue.js·typescript·canvas
m0dw1 天前
vue懒加载
前端·javascript·vue.js·typescript
流影ng2 天前
【HarmonyOS】并发线程间的通信
typescript·harmonyos
duansamve2 天前
TS在Vue3中的使用实例集合
typescript·vue3
FanetheDivine3 天前
ts中如何描述一个复杂函数的类型
前端·typescript
struggle20254 天前
AxonHub 开源程序是一个现代 AI 网关系统,提供统一的 OpenAI、Anthropic 和 AI SDK 兼容 API
css·人工智能·typescript·go·shell·powershell
执剑、天涯4 天前
通过一个typescript的小游戏,使用单元测试实战(二)
javascript·typescript·单元测试