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
相关推荐
Bolt2 小时前
TypeScript 7.0 来了:当 tsc 用 Go 重写之后
javascript·typescript·go
Flynt9 小时前
装上TypeScript 7.0 RC之后,最让我意外不是10倍提速
typescript·visual studio code
疯狂SQL9 小时前
手写高性能在线 JSON 工具|Web Worker 工程化打包 + 语法自动修复 + 多语言代码生成实战
typescript·json·next.js·web worker·前端性能优化·esbuild·源码实战
Momo__4 天前
TypeScript NoInfer<T>——精准控制泛型推断的工具类型
前端·typescript
退休倒计时5 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
kyriewen6 天前
TypeScript 高级类型:我用 infer 写了一个类型安全的 EventBus,终于搞懂了泛型约束
前端·javascript·typescript
月光刺眼6 天前
Bun + TypeScript 后端入门:从类型约束到 LLM API 调用
后端·typescript
天蓝色的鱼鱼6 天前
Node.js 现在能直接跑 TypeScript 了,tsx 和 ts-node 还需要吗?
前端·typescript·node.js
Oo9206 天前
Bun:下一代 JavaScript/TypeScript 运行时,从入门到实践
typescript·bun
Asize7 天前
Bun + TypeScript 实战:从接口约束到 RESTful 路由设计
后端·typescript·代码规范